Indexing is one of the most powerful techniques for improving the performance of MySQL queries, but it must be used wisely to get the best results. Well-optimized indexes can drastically speed up query execution by allowing MySQL to retrieve rows faster.
MySQL provides various types of indexes, each with its specific use cases:
Index Columns in WHERE, JOIN, and ORDER BY Clauses
Columns that are frequently used in WHERE, JOIN, and ORDER BY clauses should be indexed. This reduces the number of rows MySQL has to scan, making query execution faster.
SELECT * FROM users WHERE email = 'example@example.com';
In this case, creating an index on the email column would improve query performance:
CREATE INDEX idx_users_email ON users(email);
A composite index is an index on multiple columns. This is particularly useful when a query filters by multiple columns in sequence.
If you frequently query by both last_name and first_name:
SELECT * FROM employees WHERE last_name = 'Smith' AND first_name = 'John';
Creating a composite index would improve performance:
CREATE INDEX idx_employees_name ON employees(last_name, first_name);
Too many indexes can harm performance, especially for write-heavy applications (INSERT, UPDATE, DELETE). Each index requires additional disk space and increases the time needed to update the table.
SELECT * FROM sys.schema_unused_indexes;
For text-heavy search queries, use full-text indexes instead of regular indexes, as they are optimized for natural language searches.
CREATE FULLTEXT INDEX idx_description ON products(description);
Then use the MATCH function to perform full-text searches:
SELECT * FROM products WHERE MATCH(description) AGAINST('search term');
Using functions on indexed columns in the WHERE clause prevents MySQL from using the index.
SELECT * FROM employees WHERE YEAR(hire_date) = 2020;
MySQL cannot use an index on hire_date because of the YEAR() function. Instead, rewrite the query:
SELECT * FROM employees WHERE hire_date BETWEEN '2020-01-01' AND '2020-12-31';
This allows MySQL to use an index on the hire_date column.