Query Planning

The optimizer finds the cheapest road to the same answer

L215 MINDATABASES
PREDICT

The planner estimates row counts from statistics that ANALYZE collects, then picks a join: a nested loop (one index probe per row) for few rows, a hash join for many. Statistics say 0.01% of 1,000,000 orders are pending. A backfill adds 999,900 pending orders and nobody runs ANALYZE. Which join does the planner pick for the pending orders?

SQL says what you want, not how to get it. The planner chooses how. For a join it can probe an index once per row (nested loop) or build a hash table once and probe it (hash join). Which is cheaper depends on how many rows come in, and the planner does not count them. It estimates from statistics that ANALYZE gathered earlier. When the data changes and the statistics do not, the planner prices plans for a table that no longer exists.

▶ SIMULATION
PLANNER (estimates)
stats: none yet
estimated rows: —
not planned
TABLE orders (actual)
rows: 1,000,000
pending: 100
changed since ANALYZE: 0
customers: 10,000
EXECUTOR (actual)
actual rows: —
not run
last—
✓ planner row estimate within 10x of the actual rows✓ chosen plan costs at most 2x the best plan
SCHEDULE
01[DBA]ANALYZE orders (gather statistics)
02[PLANNER]plan the join from statistics
03[EXECUTOR]run the chosen plan on the real rows
Start of fresh stats scenario. 3 steps.
How the planner priced this join
================================

est_rows = (pending / rows at last ANALYZE) * rows now

nested loop  = est_rows                 fetch matching orders
             + est_rows * 8             one index probe into customers each
hash join    = est_rows                 fetch matching orders
             + 10,000 * 2               build a hash table over customers once
             + est_rows                 probe it once per order

Crossover: 9N = 2N + 20,000  ->  N ~ 2,857 rows.
Below it the nested loop wins; above it the hash join wins.

A bulk load of 999,900 pending orders changes the pending fraction from
0.01% to 50%. Scaling by table size cannot fix that: until ANALYZE runs,
the planner still believes 0.01% and estimates ~200 rows.

PostgreSQL: EXPLAIN ANALYZE prints rows=<estimate> next to actual rows=.
A gap of 10x or more is the first thing to look for in a slow plan.
Autovacuum runs ANALYZE after enough rows change, but not instantly;
run ANALYZE yourself after a bulk load.

Watch the estimate against the actual rows. In STALE STATS the estimate invariant breaks as soon as the planner runs, and the executor then pays 4.5x the best plan. One ANALYZE makes the same load harmless.

BREAK IT NOT YET

This nightly job analyzes, plans and runs the join on 100 pending orders, and the nested loop is the right call. Inject the backfill at a point where it makes the executor run a plan more than twice as expensive as the best one.

GOAL: the executed plan costs more than 2x the best plan

FIX IT NOT YET

Write the planner. Estimate the matching rows by scaling the pending fraction from the last ANALYZE to the current table size, price both plans with the formulas in the comment, and pick the cheaper. Return { est, costs: { nested_loop, hash_join }, plan }.

Mental model:

the planner is a cost model run on a guess. Join choice flips at a crossover row count, and the guess comes from statistics that are only as fresh as the last ANALYZE. When a plan goes bad overnight, compare estimated against actual rows before you touch the query.

IN PRODUCTION

EXPLAIN ANALYZE in PostgreSQL and MySQL prints estimated and actual rows side by side. Autovacuum (PostgreSQL) and persistent statistics (InnoDB) refresh statistics after enough rows change, but a bulk load or a migration can outrun them. Data pipelines often end with an explicit ANALYZE for this reason.

IN INTERVIEWS

“This query was fast yesterday and slow today. Walk me through it.” Run EXPLAIN ANALYZE, find the node where estimated and actual rows diverge, explain how that misestimate picked the wrong join or scan, refresh the statistics, and only then consider rewriting the query or adding an index.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.

USED IN

Chapters that build on this lesson.

NEXT: INDEXES & SELECTIVITY →