Reading a query plan

Everything in the previous lesson was a claim about what the engine would do. This lesson is how to find out what it did.

Being able to read a plan is the single highest-leverage SQL skill in a backend interview, because it turns “I think this is slow because of the join” into a sentence with a number in it.

EXPLAIN versus EXPLAIN ANALYZE

EXPLAIN SELECT * FROM employee WHERE department_id = 2;

EXPLAIN shows the plan the planner chose, with estimates. It does not run the query.

EXPLAIN ANALYZE SELECT * FROM employee WHERE department_id = 2;

EXPLAIN ANALYZE runs the query and adds what actually happened. That matters twice over:

  • The actual numbers are what you need.
  • It really executes. EXPLAIN ANALYZE DELETE ... deletes. Wrap it in a transaction and roll back if the statement writes:
BEGIN;
EXPLAIN ANALYZE DELETE FROM sale WHERE amount < 5000;
ROLLBACK;

How to read the shape

A plan is a tree, printed with the innermost, most-indented node first in execution order and last in the output. Read it bottom-up: the deepest nodes produce rows, their parents consume them.

For a plan like

Sort
  -> Hash Join
       -> Seq Scan on employee
       -> Hash
            -> Seq Scan on department

the two scans happen first, the department rows are built into a hash table, the employee rows are probed against it, and the result is sorted.

The two numbers that find the problem

Every EXPLAIN ANALYZE node carries something like:

(cost=0.00..1.09 rows=2 width=48) (actual time=0.011..0.013 rows=2 loops=1)

The first parenthesis is the estimate, the second is actual.

1. Compare rows estimated against rows actual. This is the first thing to look at, every time. The planner chooses strategies based on estimated row counts, so if it expected 2 rows and got 200,000, every decision above that node was made on bad information — and the fix is usually statistics (ANALYZE table) or a predicate the planner cannot estimate, not a different index.

A large divergence is the single most common root cause of a plan that looks insane.

2. Look at loops. A node with loops=5000 ran five thousand times, and its reported time is per loop — so the total is time multiplied by loops. This is where a correlated subquery or a nested loop over a large outer side shows up, and it is easy to miss because the per-loop time looks tiny.

The three join strategies

Knowing which one you are looking at, and when each is right, covers most of what gets asked:

Nested Loop. For each row on the outer side, look up matches on the inner side. Excellent when the outer side is small and the inner lookup is indexed; catastrophic when the outer side is large, because the cost is outer rows multiplied by the inner lookup.

Hash Join. Build a hash table from one side, probe it with the other. The usual choice for joining two large unsorted sets on equality. Needs memory for the hash; if it does not fit in work_mem it spills to disk in batches, which the plan reports and which is a strong signal to look at memory or at reducing the row count earlier.

Merge Join. Both sides sorted on the join key, then walked together in one pass. Cheap when the inputs are already sorted — typically because an index provides the order — and otherwise it has to pay for the sorts.

Only hash and merge joins require equality. A join on < or a range can only be a nested loop, which is why a range join over two big tables is expensive no matter what you index.

Node types worth recognising

Node What it means
Seq Scan Read the whole table. Correct when the query is unselective.
Index Scan Walk the index, fetch each matching row from the table.
Index Only Scan Answered from the index alone — no heap fetch.
Bitmap Heap Scan Collect matches in the index, sort them by page, then read the table in page order. The planner’s middle path when there are too many matches for an index scan and too few for a seq scan.
Sort An explicit sort. Check Sort Method: quicksort in memory is fine, external merge Disk means it spilled.
Hash Building the hash table for a hash join.
Materialize Caching a subtree’s output because it will be re-read.

A Filter line under a scan with a large Rows Removed by Filter is its own finding: the engine read those rows and threw them away, which is exactly what an index on the filtered column would avoid.

A worked read

EXPLAIN ANALYZE
SELECT d.name, count(*) AS n
FROM employee e
JOIN department d ON d.id = e.department_id
GROUP BY d.name
ORDER BY n DESC;

On seven rows this is a couple of sequential scans, a hash join, a hash aggregate and a sort, and every number is a rounding error. The shape is still the thing to practice reading: scans at the bottom, join above them, aggregate above that, sort at the top — which is the logical order of operations from the first lesson made visible.

To see a plan where the numbers matter you need volume:

CREATE TABLE big AS
SELECT g AS id, (g % 500) AS bucket, md5(g::text) AS payload
FROM generate_series(1, 50000) g;
EXPLAIN ANALYZE SELECT count(*) FROM big WHERE bucket = 7;
CREATE INDEX idx_big_bucket ON big (bucket);
EXPLAIN ANALYZE SELECT count(*) FROM big WHERE bucket = 7;

Fifty thousand rows, a hundred matching per bucket — selective enough that the second plan should change. Run both and compare.

DROP TABLE big;

What to say in an interview

Given a slow query, the order that gets to an answer fastest:

  1. EXPLAIN ANALYZE it.
  2. Find the node where estimated and actual rows diverge most. Bad estimates cause bad plans, and no index fixes a bad estimate.
  3. Find the node with the largest time multiplied by loops. That is where the work is, not where the plan looks ugliest.
  4. Only then ask whether an index, a rewrite, or more work_mem is the fix.

Saying “I would check the estimated against actual row counts first” is a stronger answer than naming any particular index.

Try it

The big table sequence above is the one worth running in the SQL playground — it is the smallest example where building an index visibly changes a plan.

Drill it with Recent hires by department.

Interview questions

1. What is the difference between EXPLAIN and EXPLAIN ANALYZE? EXPLAIN shows the chosen plan with estimates and does not execute. EXPLAIN ANALYZE executes the query and reports actual times and row counts — including for statements that write, which is why those go inside a transaction you roll back.

2. In a plan, what is the first thing you look at? The divergence between estimated and actual rows. The planner’s choices follow from its estimates, so a large error upstream explains a bizarre plan downstream, and the fix is statistics rather than an index.

3. What does loops=5000 mean for the reported time? The node ran 5,000 times and the time shown is per loop, so the real cost is the product. It is the signature of a nested loop over a large outer side or a correlated subquery the planner could not rewrite.

4. Name the three join strategies and when each is appropriate. Nested loop for a small outer side with an indexed inner lookup; hash join for two large sets on equality; merge join when both inputs are already sorted on the key. Only hash and merge require an equality condition.

5. What is a bitmap heap scan for? Too many matches for a plain index scan and too few for a sequential scan. It collects the matching locations from the index, sorts them by page, then reads the table in page order to make the I/O sequential.

6. A plan shows Sort Method: external merge Disk. What does that tell you? The sort did not fit in work_mem and spilled to disk. Either reduce the rows being sorted, avoid the sort with an index that supplies the order, or raise work_mem for that workload.

Next

The N+1 problem — the slow query that never appears in a slow-query log.