Query Processing & Optimization
How a SQL query is parsed, rewritten, planned and executed — cost-based optimisation, statistics, join ordering, reading EXPLAIN plans, and practical tuning.
SQL says what you want. The database's query optimiser decides how to get it — which indexes to use, which join algorithm, in what order — choosing among thousands of possible plans. Understanding that process lets you read query plans and fix slow queries.
The pipeline
- Parse — check syntax and build a tree; resolve table and column names, check permissions.
- Rewrite — expand views, apply rules, simplify expressions.
- Optimise — generate candidate plans, estimate the cost of each, pick the cheapest.
- Execute — run the plan: a tree of operators pulling rows from their children (the iterator or "Volcano" model), or vectorised batches in analytical engines.
Plans can be cached for prepared statements, which saves the planning cost on repeated queries.
Plan operators
| Operator | Does |
|---|---|
| Seq Scan | Read the whole table |
| Index Scan | Walk the index, fetch each matching row from the table |
| Index Only Scan | Answer from the index alone (covering) |
| Bitmap Index/Heap Scan | Collect matching row locations from one or more indexes, then fetch pages in physical order |
| Nested Loop / Hash Join / Merge Join | Join algorithms (SQL joins) |
| Sort, Hash Aggregate, Group Aggregate | ORDER BY, GROUP BY |
| Limit | Stop early — can make index-ordered plans very cheap |
Cost-based optimisation
The optimiser estimates each plan's cost (I/O pages plus CPU work) from statistics:
- Row counts and page counts per table.
- Per-column: number of distinct values, NULL fraction, most common values, histograms of the distribution.
- Sometimes multi-column statistics (
CREATE STATISTICSin Postgres) for correlated columns.
From these it estimates selectivity — what fraction of rows a predicate keeps — and hence row counts through the plan. Example: WHERE country = 'NZ' on 10M rows with NZ at 0.5% → ~50,000 rows → an index scan is probably worthwhile.
Join ordering
For n tables there are roughly n! join orders (times algorithm choices). Optimisers use dynamic programming over subsets of tables (System R style) for small joins and heuristics or genetic search for very large ones (Postgres switches to GEQO above 12 tables). The goal is to keep intermediate results small: filter early, join the most selective tables first.
Classic rewrites the optimiser does
- Predicate pushdown — apply filters as early as possible, before joins.
- Projection pushdown — read only the needed columns.
- Subquery unnesting — turn
IN/EXISTSsubqueries into semi-joins. - Constant folding, removing redundant joins, using constraints to prove conditions false.
Reading EXPLAIN
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, o.total
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE c.country = 'NZ' AND o.created_at > now() - interval '7 days';Hash Join (cost=1250.3..9870.1 rows=820 width=16) (actual time=12.1..48.7 rows=791 loops=1)
Hash Cond: (o.customer_id = c.id)
-> Index Scan using idx_orders_created on orders o
(cost=0.43..8350.2 rows=41000 width=24) (actual time=0.03..30.2 rows=40211 loops=1)
Index Cond: (created_at > (now() - '7 days'::interval))
-> Hash (cost=1100.0..1100.0 rows=12000 width=8) (actual time=11.8..11.8 rows=11890 loops=1)
-> Seq Scan on customers c (cost=0.00..1100.0 rows=12000 width=8)
Filter: (country = 'NZ')
Rows Removed by Filter: 488110
Planning Time: 0.4 ms
Execution Time: 49.3 msHow to read it:
- It's a tree; execution starts at the most-indented nodes.
cost=start..totalis in the planner's abstract units;actual timeis in milliseconds (per loop).- Compare
rows(estimated) withactual rows— large gaps mean bad statistics. - Watch for
loopsmultiplying the cost of inner nodes in nested loops. Rows Removed by Filter: 488110— the scan read 500k rows to keep 12k; an index oncustomers(country)might help.BUFFERSshows pages read from cache (hit) vs disk (read).
Tools like explain.depesz.com and pgMustard visualise plans; MySQL has EXPLAIN ANALYZE and EXPLAIN FORMAT=TREE.
Practical tuning checklist
- Find the slow queries:
pg_stat_statements, MySQL's slow query log, APM traces. Optimise by total time (frequency × duration), not just the slowest single query. EXPLAIN ANALYZEthem. Look for sequential scans of big tables, bad estimates, huge sorts spilling to disk, and nested loops over many rows.- Fix with indexes (composite, covering, partial), sargable predicates (no functions on indexed columns), and fresh statistics.
- Reduce work: select only needed columns, paginate with keyset pagination (
WHERE id > last_seen ORDER BY id LIMIT 50) instead of largeOFFSETs, avoid N+1 query patterns in ORMs. - Then consider caching, materialised views, read replicas, or schema changes.
- Parse → rewrite → optimise → execute; the optimiser picks the cheapest of many plans.
- Costs come from statistics; wrong row estimates are the main cause of bad plans.
- Join order matters; the optimiser searches it with dynamic programming and heuristics.
- In EXPLAIN ANALYZE compare estimated vs actual rows, find scans, sorts and loops.
- Tune: find top queries by total time, index well, keep predicates sargable, avoid OFFSET and N+1.