How a Query Actually Runs
Parser to plan to execution — join algorithms, cost models, why the optimizer picks the wrong plan, and what "vectorized execution" buys you.
#From text to results
SQL is declarative: you state what you want, not how to get it. Everything between the string you send and the rows you receive is the database deciding how, and that decision can vary the runtime by four orders of magnitude on identical data.
- 1 Parse SQL text → syntax tree
- 2 Bind resolve names, types, permissions
- 3 Rewrite views, subquery flattening, predicate pushdown
- 4 Optimize enumerate plans, estimate cost, pick one
- 5 Execute run the operator tree
The rewrite stage turns the query into an equivalent but easier one. Two examples: subquery flattening turns a nested WHERE id IN (SELECT ...) into an ordinary join, and predicate pushdown moves a WHERE filter as close to the table scan as possible, so rows are thrown away early instead of being carried through joins first.
The optimizer is where the interesting failures happen, and it fails for one structural reason: it is guessing. It cannot know how many rows your WHERE clause will actually match without running it, so it estimates from statistics it collected earlier — roughly, "how many distinct values does this column have, and how are they spread out". When the estimate is wrong, the plan is wrong, and the plan being wrong is what a "mysteriously slow query" almost always is.
#The operator tree
A plan is a tree of operators, each pulling rows from its children. The classic model — Volcano/iterator — gives every operator a next() method that returns one row.
SELECT u.name, count(*)
FROM users u JOIN orders o ON o.user_id = u.id
WHERE u.country = 'IN' AND o.created_at > '2026-01-01'
GROUP BY u.name
┌─────────────────────┐
│ HashAggregate │ group by u.name
└──────────┬──────────┘
┌──────────┴──────────┐
│ Hash Join │ o.user_id = u.id
└────┬───────────┬────┘
│ │
┌─────────┴──┐ ┌────┴────────────┐
│ Index Scan │ │ Seq Scan │
│ users │ │ orders │
│ country=IN │ │ created_at > .. │
└────────────┘ └─────────────────┘
Rows flow UP. Each operator pulls from its children on demand.Reading a plan is reading this tree from the leaves inward: what is scanned, how it's filtered, how the intermediate results are combined, and how many rows the optimizer thought would flow along each edge versus how many actually did.
#The three join algorithms
Nearly every join in every relational database is one of three, and knowing which one is appropriate is most of query tuning.
Two terms first. In a nested loop, the outer side is the table you loop over, and the inner side is the one you search once per outer row. In a hash join, the build side is the table loaded into an in-memory hash table; the other side is then streamed past it.
| Algorithm | Cost | Best when | Fails when |
|---|---|---|---|
| Nested loop | O(N × M), or O(N × log M) with an index | Outer side is tiny; inner side is indexed | Outer side is large — the classic 10,000× blowup |
| Hash join | O(N + M), needs memory for the build side | Large unsorted inputs, equality predicate | Build side doesn't fit memory → spills to disk |
| Merge join | O(N + M), but requires sorted inputs | Inputs already sorted (index order, or previously sorted) | Sorting first costs O(N log N) |
NESTED LOOP HASH JOIN MERGE JOIN
for each row in A: build hash table on B both inputs sorted
look up matches in B (smaller side) walk two cursors
for each row in A: in lockstep
→ great if A has 10 rows probe the table
and B is indexed → zero memory
→ catastrophic if A has → one pass over each → free if the inputs
10M rows side, but B must arrive sorted
fit in memoryThe classic production incident: statistics say a filter returns 10 rows, so the optimizer picks a nested loop. Reality is 2 million rows. The plan does 2 million index lookups instead of one hash build, and a query that should take 200 ms takes 40 minutes. Nothing changed except the data distribution.
#Cardinality estimation, and why it's hard
Everything hinges on one number per operator: how many rows will come out of this? Get it right and the plan is usually right. Get it wrong and it compounds up the tree.
Estimation works from statistics gathered by sampling:
- Histograms — the value distribution of a column, in buckets. Answers "how many rows have
age > 40?" - Distinct counts (NDV, "number of distinct values") — how many unique values. Drives join size estimates: if
ordershas 1M rows and 100K distinctuser_ids, the optimizer assumes each user matches about 10 orders. - Most-common-values lists — explicit counts for skewed values, so a value that's 30% of the table isn't averaged away.
- Correlation — how well the physical row order on disk matches the index order. If they match, the rows an index scan wants sit next to each other (sequential I/O); if not, each row is somewhere else on disk (random I/O).
This is a fundamental limitation, not an implementation gap. It's why some systems now use adaptive execution: start executing, count the rows actually produced, and re-plan the remainder if reality diverges from the estimate. Spark's AQE and modern SQL Server both do this.
#Reading EXPLAIN properly
EXPLAIN asks the database what it intends to do. EXPLAIN ANALYZE actually runs the query and reports what happened — including the real row counts next to the estimated ones, which is the comparison that finds the problem. It's the only version worth looking at.
What to look for, in order:
- Estimated vs actual rows at every node. This is the single highest-value signal. A 1000× discrepancy tells you the optimizer was working from bad information, and everything above that node is consequently wrong.
- The most expensive node, not the top one. Time is reported cumulatively in most systems; you want the node where it was actually spent.
- Sequential scan on a large table where you expected an index. Usually means the index is unusable — a function applied to the column (
WHERE lower(email) = ...can't use an index onemail), a type mismatch, a leading wildcard (LIKE '%son'— the index is sorted by the start of the string), or the optimizer correctly deciding the index isn't selective enough (the filter matches so much of the table that reading it all is cheaper). - Spills to disk. "Sort Method: external merge, Disk: 480MB" means
work_memwas too small and the sort went to disk — often a 10–100× penalty for a config value. - Nested loop with a large outer side. The blowup described above.
- Rows removed by filter. If a scan reads 10M rows and filters out 9.99M, you needed a different index.
#Vectorized execution
The Volcano model's next()-per-row design has an overhead problem. For every single row, each operator has to call its child's next() through a generic interface (the CPU can't know in advance which code will run), check what kind of operator it is, and load that operator's bookkeeping — all to process one value. That fixed cost per row can be bigger than the actual work, like adding two numbers.
ROW-AT-A-TIME (Volcano) VECTORIZED (batch-at-a-time)
for each row: for each batch of ~1,024 rows:
next() → virtual call process the whole batch
branch on operator type in a tight loop
process 1 value
~50-200 ns of overhead overhead amortised over 1,024 rows
per row per operator → ~1-5 ns per row
→ the loop vectorizes to SIMD
→ branch predictor actually works
→ data stays in L1/L2The three arrows on the right are what "a loop the CPU can optimise" means. SIMD instructions process 4–16 values in one instruction. The branch predictor (the CPU's guess about which way an if goes) is almost always right when it's the same loop over and over. And a batch is small enough to stay in the fastest L1/L2 caches, so the CPU isn't waiting on main memory.
The gain is 10–100× on analytical scans. It comes entirely from spreading the fixed per-call cost of walking the operator tree (the "interpreter overhead" — the engine is effectively interpreting the plan) over 1,024 rows instead of one, and giving the CPU that kind of loop. Combined with a columnar layout — where a batch is a contiguous run of one column's values — it's the reason modern analytical engines (DuckDB, ClickHouse, Velox, Photon) are so much faster than traditional row engines on the same hardware.
The other approach is compilation: generate machine code for the specific query, eliminating the interpreter entirely. Faster still for long queries, but it pays a compile cost per query, so systems typically compile only when the query is expected to run long enough to earn it.
#Exercise
#Check yourself
Why do query plans go wrong?Show answer
When is each join algorithm right?Show answer
What is the classic nested-loop disaster?Show answer
Name the three causes of a plan going bad with no code change.Show answer
Why are deep join trees fragile?Show answer
What do you look at first in EXPLAIN ANALYZE?Show answer
What does vectorized execution buy, and where doesn't it help?Show answer
#What to carry forward
- The plan, not the SQL, determines runtime — and the plan hinges on cardinality estimates, the optimizer's guesses about how many rows each step will produce.
- Three join algorithms, each with a regime where it's right and one where it's catastrophic.
- Estimation errors multiply up the tree, which is why deep join trees are fragile.
- Read
EXPLAIN ANALYZEfor estimated vs actual rows first; everything else is downstream of that ratio. - Vectorized execution amortises interpreter overhead over batches — a 10–100× analytical win, and no help at all for point lookups.