MySQL · Query diagnosis
A slow MySQL query: an index is a hypothesis
Follow a sample query from filters to a candidate index, then measure the read benefit, write cost and correct results.
A page needs the latest 50 orders, but the customer waits. Before adding an index, identify which database work it could remove. Then compare the candidate with today’s plan under the same workload.
The short version
What to take away
- Diagnose the user-visible delay before selecting an index candidate.
- Treat EXPLAIN as estimates and remember EXPLAIN ANALYZE executes the query.
- Test the candidate against representative reads, writes and result correctness.
The query and the candidate
For a hypothetical MySQL 8.4 InnoDB orders table, the application asks for one customer’s newest paid orders. The question-mark placeholders are bound parameters:
SELECT order_id, created_at, total
FROM orders
WHERE customer_id = ? AND status = ?
ORDER BY created_at DESC
LIMIT 50;A candidate index sequence is (customer_id, status, created_at): two equality filters followed by the ordering column. With both equality values fixed, an appropriate ordered access path may reduce filtering or sorting work.
This is a hypothesis, not a command to create an index. Existing indexes, value distribution and related queries affect the decision. The candidate does not necessarily cover every selected column, including total. If equal timestamps require a deterministic tie-breaker, include that requirement in the query and evaluation.
Measure three things
- User-visible delay: separate execution time from connection waits, network transfer and application work. An index will not fix every layer.
- Database work: inspect EXPLAIN’s chosen key, estimated rows and operations. Compare customers with few and many orders and common versus uncommon status values. Estimates are not measured execution.
- Wider cost: compare repeatable latency and correct results alongside related reads, write throughput and storage. Additional indexes add maintenance work to inserts, updates and deletes.
Keep parameters, data volume, concurrency and cache conditions comparable between baseline and candidate. Define acceptable improvement and regression limits before testing. Keep, revise or reject the candidate using that evidence, rather than one favorable timing.
Two cautions worth remembering
EXPLAIN ANALYZE executes the statement. Use it only in an appropriate controlled environment with understood resource limits. A filesort indicates an extra sorting operation; its name alone does not prove disk use.
No benchmark results are claimed here. Before any schema change, obtain rollout approval and define observation and reversal steps; ordinary transaction rollback may not undo DDL.
Official MySQL 8.4 sources: multiple-column indexes, EXPLAIN, ORDER BY optimization and implicit commits.