MySQL Composite Indexes
A composite index in MySQL is an index that includes more than one column, allowing for more efficient querying on those columns. It is used to speed up retrieval operations on a database table when queries frequently involve multiple columns.
Usage
Composite indexes are used when queries involve conditions on multiple columns, especially with WHERE
, ORDER BY
, or GROUP BY
clauses. They are created to optimize query performance by minimizing the number of rows to scan.
CREATE INDEX index_name
ON table_name (column1, column2, ...);
In this syntax, index_name
is a unique identifier for the index, table_name
is the table on which the index is created, and column1, column2, ...
are the columns that make up the composite index.
Examples
1. Basic Composite Index
CREATE INDEX idx_customer_name
ON customers (last_name, first_name);
This example creates a composite index on the customers
table, optimizing queries that search by last_name
and first_name
.
2. Optimizing Query with WHERE Clause
CREATE INDEX idx_order_date_customer
ON orders (order_date, customer_id);
SELECT * FROM orders
WHERE order_date = '2023-10-01' AND customer_id = 1001;
Here, a composite index on order_date
and customer_id
helps efficiently execute queries filtering by both fields.
3. Impact of Index Column Order
CREATE INDEX idx_product_category_price
ON products (category_id, price);
SELECT * FROM products
WHERE category_id = 5 AND price < 100;
In this example, the order of columns in the index affects query performance. Placing the more selective column (category_id
) first can improve efficiency.
4. Covering Index
CREATE INDEX idx_sales_date_product
ON sales (sale_date, product_id, quantity);
SELECT sale_date, product_id, quantity
FROM sales
WHERE sale_date BETWEEN '2023-01-01' AND '2023-12-31';
A covering index includes all columns needed by the query, allowing it to be resolved using the index alone, which reduces data retrieval time from the table.
Tips and Best Practices
- Select columns wisely. Choose columns that are frequently used together in queries, especially in
WHERE
,ORDER BY
, andGROUP BY
clauses. - Order matters. Place the most selective column first in the composite index to improve efficiency.
- Keep it minimal. Avoid adding unnecessary columns to the composite index as it can increase maintenance overhead.
- Analyze query patterns. Regularly review query patterns to ensure composite indexes remain relevant and beneficial.
- Monitor performance. Use tools like
EXPLAIN
to analyze query performance and the effectiveness of your indexes. - Consider limitations. Composite indexes can increase storage and maintenance costs, so balance the benefits with these potential downsides.