Slow-Query Runbook in SQL
EXPLAIN first — access paths before rewrites
Diagnose before guessing: EXPLAIN (ANALYZE, BUFFERS) first — find misestimated/scan-heavy node. Check stats freshness, missing indexes on join/filter keys, sargability, fan-out before aggregates. Fix access paths, re-measure, keep the faster plan. Rewrite (CTE shape, EXISTS vs IN, pre-aggregation) only after access is sound.
EXPLAIN ANALYZE first
Estimates vs actuals gap locates the misplanned node. Never guess-index.
Check access trio
Stats fresh? Indexes on JOIN/WHERE? Predicates sargable (bare columns)?
Check shape
Fan-out before agg? CTE fence? IN vs EXISTS? SELECT * width?
Fix, re-measure, precompute
One variable at a time; keep winner with proof; rollups/caches past per-query ceilings.
1EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM employees WHERE department = 'Sales';
| plan | verdict |
|---|---|
| Seq Scan | healthy on 6 rows |
| Index Scan | wins past thousands with selective filter |
Six-row Seq Scan is correct — index overhead exceeds scan cost. Same plan on six million with 2% selectivity is the bug; composite on (department) is the fix. Measure-first beats guess-indexing.
30-second dashboard triage
Methodology beats guessing.
1EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM employees WHERE department = 'Sales';
| phase | check |
|---|---|
| diagnose | EXPLAIN gap |
| access | stats/index/sargability |
| shape | fan-out/fence/width |
Narrow before widening
Filter early, project narrowly.
1-- wide: SELECT * then filter2-- narrow: SELECT name, salary ... WHERE ... (indexed) before JOIN width
| shape | cost |
|---|---|
| wide | heap-heavy |
| narrow | index-friendly |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.