Chapter 4 introduced indexes and EXPLAIN. This chapter is the deep version: reading a plan line by line, designing composite indexes that queries actually use, avoiding the patterns that silently disable them, and finding which queries are worth your time.
Reading EXPLAIN
The columns that matter most, and what you want to see:
| Column | Good sign |
|---|---|
| type | const/eq_ref/ref/range — not ALL (full scan) |
| key | the index actually chosen (not NULL) |
| rows | a small estimate of rows examined |
| Extra | avoid "Using filesort"/"Using temporary" on big data |
EXPLAIN ANALYZESELECT * FROM students WHERE programme_id = 3 AND package > 8ORDER BY package DESC;-- ANALYZE actually runs it and shows real timings, not just estimates.
Designing indexes
A composite index serves queries that filter its columns left-to-right. Order matters: put equality columns first, then the range/sort column:
-- For: WHERE programme_id = ? AND package > ? ORDER BY packageCREATE INDEX idx_prog_pkg ON students(programme_id, package);-- Equality (programme_id) first, then the range/sort column (package).-- This one index handles the filter AND the sort — no filesort needed.
Index-killing patterns
- Function on the column —
WHERE YEAR(enrolled) = 2026can't use an index onenrolled. Rewrite as a range:enrolled >= '2026-01-01' AND enrolled < '2027-01-01'. - Leading wildcard —
LIKE '%term'can't use an index;LIKE 'term%'can. - Implicit type mismatch — comparing a string column to a number forces a scan.
- OR across different columns — often defeats indexing; a
UNIONof two indexed queries can be faster.
Finding slow queries
Don't guess — measure. Enable the slow query log to capture the real offenders:
SET GLOBAL slow_query_log = ON;SET GLOBAL long_query_time = 0.5; -- log anything over 0.5s-- Then analyse the log (e.g. with mysqldumpslow) to find the top offenders.
Practice
Take a query filtering and sorting on two columns; add a composite index in the right order and confirm EXPLAIN drops the filesort. Rewrite a YEAR(col) = filter as a date range and watch the index get used. Enable the slow query log and find your slowest query.
Key takeaways
- 01In EXPLAIN want type≠ALL, a chosen key, low rows, and no filesort/temporary on big data.
- 02EXPLAIN ANALYZE runs the query and shows real timings, not just estimates.
- 03Composite index order: equality columns first, then the range/sort column; covering indexes answer from the index alone.
- 04Functions on columns, leading %-wildcards, type mismatches and cross-column OR all disable indexes.
- 05Use the slow query log to find the queries actually worth optimizing — measure, don't guess.
