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.

Advanced 4 min readLesson 8 of 14

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

ParserSQL → parse treeRewriterviews, rulesOptimizerchoose the cheapest planExecutorrun the plan tree
  1. Parse — check syntax and build a tree; resolve table and column names, check permissions.
  2. Rewrite — expand views, apply rules, simplify expressions.
  3. Optimise — generate candidate plans, estimate the cost of each, pick the cheapest.
  4. 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

OperatorDoes
Seq ScanRead the whole table
Index ScanWalk the index, fetch each matching row from the table
Index Only ScanAnswer from the index alone (covering)
Bitmap Index/Heap ScanCollect matching row locations from one or more indexes, then fetch pages in physical order
Nested Loop / Hash Join / Merge JoinJoin algorithms (SQL joins)
Sort, Hash Aggregate, Group AggregateORDER BY, GROUP BY
LimitStop 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 STATISTICS in 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/EXISTS subqueries into semi-joins.
  • Constant folding, removing redundant joins, using constraints to prove conditions false.

Reading EXPLAIN

SQL
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 ms

How to read it:

  • It's a tree; execution starts at the most-indented nodes.
  • cost=start..total is in the planner's abstract units; actual time is in milliseconds (per loop).
  • Compare rows (estimated) with actual rows — large gaps mean bad statistics.
  • Watch for loops multiplying the cost of inner nodes in nested loops.
  • Rows Removed by Filter: 488110 — the scan read 500k rows to keep 12k; an index on customers(country) might help.
  • BUFFERS shows 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

  1. 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.
  2. EXPLAIN ANALYZE them. Look for sequential scans of big tables, bad estimates, huge sorts spilling to disk, and nested loops over many rows.
  3. Fix with indexes (composite, covering, partial), sargable predicates (no functions on indexed columns), and fresh statistics.
  4. Reduce work: select only needed columns, paginate with keyset pagination (WHERE id > last_seen ORDER BY id LIMIT 50) instead of large OFFSETs, avoid N+1 query patterns in ORMs.
  5. Then consider caching, materialised views, read replicas, or schema changes.
Key takeaways
  • 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.