4.4.15 · D3Databases

Worked examples — EXPLAIN — reading query plans, cost estimation

3,476 words16 min readBack to topic

Before we start, let me re-anchor the four symbols so you never have to scroll up:

Throughout, our table is orders with and , so stays fixed. Only moves — and is what decides everything.


The scenario matrix

Every question this topic can ask is one of these cells. The examples below are labelled with the cell they cover so you can see nothing is skipped.

Cell Case class What is special about it Example
A Very low selectivity () index crushes seq scan Ex 1
B Very high selectivity () seq scan crushes index Ex 2
C The break-even point where the planner flips Ex 3
D Degenerate: empty table () costs collapse, no divide-by-zero traps Ex 4
E Degenerate: predicate matches 0 rows () index is nearly free Ex 4
F Startup-vs-total with LIMIT low startup wins even at high total Ex 5
G A blocking operator (Sort) startup = total, must read all input Ex 5
H A join (nested loop, two tables) costs multiply, not add Ex 6
I Word problem (real dashboard) translate English → → decision Ex 7
J Exam twist: stale stats estimate right, reality wrong Ex 8
Figure — EXPLAIN — reading query plans, cost estimation

The picture above is the spine of the whole page: cost on the y-axis, selectivity on the x-axis. The flat orange line is the seq scan (it ignores ). The rising teal line is the index scan (it grows with ). Where they cross is cell C. Left of the cross → cell A (index wins). Right → cell B (seq wins). Keep glancing back at it.


Cell A — very low selectivity


Cell B — very high selectivity


Cell C — the break-even point

We derive where the two lines in the figure cross. Set and ignore the tiny tree-descent term:

We write the break-even value with a star, , to mean "the special where the two plans tie."


Cells D & E — the degenerate inputs


Cells F & G — startup cost, blocking operators, and LIMIT

Now we leave single scans and add a Sort, then a LIMIT. First we must earn two words the parent used but this page has not yet nailed down.


Cell H — a join


Cell I — the word problem


Cell J — the exam twist: stale statistics


Recall Self-test — cover the answers

Which cell wins the index and which wins the seq scan? ::: Index for low (cell A, left of crossover); seq for high (cell B, right of crossover). What is the break-even selectivity for our orders table? ::: About , i.e. rows, from . Why does LIMIT 10 not speed up a Sort? ::: Sort is a blocking operator — startup ≈ total; with the LIMIT formula gives no discount. In a nested loop, do inner costs add or multiply? ::: Multiply — inner runs once per surviving outer row (loops=). What does rows=200000 ... actual rows=900000 tell you? ::: A 4.5× estimation error, classic stale-statistics symptom; run ANALYZE.