Let's optimize a MySQL query by using indexes effectively. Consider a scenario where we have a table named orders
with the following structure:
CREATE TABLE orders ( id INT PRIMARY KEY, customer_id INT, order_date DATE, total_amount DECIMAL(10,2), INDEX idx_customer_id (customer_id), INDEX idx_order_date (order_date) );
Suppose we want to retrieve orders for a specific customer within a certain date range and we want to optimize this query.
Here's the original query:
SELECT * FROM orders WHERE customer_id = 12345 AND order_date BETWEEN '2024-01-01' AND '2024-01-31';
To optimize this query, we can:
-
Use Composite Index: Create a composite index on
(customer_id, order_date)
to cover both filtering conditions in the WHERE clause efficiently. -
**Avoid SELECT ***: Instead of selecting all columns usin