Reading an Execution Plan Node by Node
Load a two-million-row shop dataset, take one slow dashboard query apart with EXPLAIN (ANALYZE, BUFFERS), and learn to find the plan node that actually costs the most.
Contentsand lesson path
On this page
- The brief
- Step 1: read the tree, innermost first
- Step 2: compare estimates with reality, find the expensive node
- Step 3: what the default parallel plan adds
- Step 4: change one thing and re-read
- Common plan-reading mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Indexing & Query Optimization
- How a B-Tree Index Finds Your Rows Concept · 20 min
- Reading an Execution Plan Node by Node Worked example · 30 min
- Lab: Designing Indexes for a Workload, Text Search Included Lab · 30 min
- Index-Friendly Rewrites and Fresh Statistics Lab · 25 min
- Finding the Queries That Actually Matter Lab · 20 min
- Check: Diagnose Three Slow Queries Knowledge check · 8 questions
What you will learn
- Read EXPLAIN (ANALYZE, BUFFERS) output to identify scan and join methods, row-estimate errors and the most expensive plan node.
Prerequisites: SQL Fundamentals
01. The brief
The shop schema from the modelling worked example is live, and a dashboard query is slow: the twenty largest orders placed by German customers since September. You get the query, a database, and one command that explains everything: EXPLAIN ANALYZE. Your job is not to guess why it is slow — it is to read the machine's own account of what it did.
Load the dataset into the qopt-lab container from the previous lesson. It is the same shape as demo_orders, scaled to 50,000 customers, 200,000 products and two million orders. This generate-and-insert takes about a minute on a small machine; the dataset then serves the rest of the skill.
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE,
full_name text NOT NULL,
country text NOT NULL,
created_at timestamptz NOT NULL
);
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL UNIQUE,
name text NOT NULL,
price numeric(10,2) NOT NULL CHECK (price >= 0)
);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers(id),
status text NOT NULL,
total numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL
);
SELECT setseed(0.42);
INSERT INTO customers (email, full_name, country, created_at)
SELECT 'customer' || g || '@example.com',
(ARRAY['Ana','Ben','Clara','Dmitri','Elif','Farad','Grace','Hugo',
'Ines','Jonas'])[(g % 10) + 1] || ' ' ||
(ARRAY['Meyer','Silva','Novak','Okafor','Khan','Rossi','Dubois',
'Larsen','Patel','Weber'])[(g % 7) + 1],
(ARRAY['DE','FR','US','GB','NL'])[(g % 5) + 1],
timestamptz '2024-01-01' + (random() * 500) * interval '1 day'
FROM generate_series(1, 50000) g;
INSERT INTO products (sku, name, price)
SELECT 'SKU-' || lpad(g::text, 6, '0'),
(ARRAY['Wireless','Wired','Ergonomic','Compact','Gaming','Silent',
'Mechanical','Bluetooth','Rechargeable','Ultra-Thin'])[(g % 10) + 1]
|| ' ' ||
(ARRAY['Mouse','Keyboard','Headset','Webcam','Monitor','Laptop Stand',
'USB Hub','Trackpad','Speaker','Microphone'])[(g % 9) + 1]
|| ' ' ||
(ARRAY['Black','White','Blue','Silver','Space Grey','Rose'])[(g % 6) + 1]
|| ' M' || ((g % 9) + 1)::text,
round((random() * 480 + 19.50)::numeric, 2)
FROM generate_series(1, 200000) g;
INSERT INTO orders (customer_id, status, total, created_at)
SELECT (random() * 49999)::int + 1,
CASE WHEN r < 0.015 THEN 'pending'
WHEN r < 0.06 THEN 'cancelled'
WHEN r < 0.25 THEN 'shipped'
ELSE 'completed' END,
round((random() * 480 + 9.90)::numeric, 2),
timestamptz '2025-01-01' + (random() * 669) * interval '1 day'
FROM (SELECT g, random() AS r FROM generate_series(1, 2000000) g);
ANALYZE customers;
ANALYZE products;
ANALYZE orders;Run the slow query under EXPLAIN (ANALYZE, BUFFERS). ANALYZE executes the query and reports real times and row counts next to the planner's estimates; BUFFERS reports page reads, which usually explain the times. Because ANALYZE really runs the statement, an EXPLAIN ANALYZE of an UPDATE, DELETE or INSERT changes data and fires triggers: wrap it in BEGIN; ... ROLLBACK; when you only want the plan. Postgres may answer in parallel by default; for this first reading, switch parallel workers off so the tree has no moving parts, knowing the default plan comes back later:
SET max_parallel_workers_per_gather = 0;
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.email, o.id, o.total
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE c.country = 'DE'
AND o.created_at >= timestamptz '2026-09-01'
ORDER BY o.total DESC
LIMIT 20;Limit (cost=46004.16..46004.21 rows=20 width=39)
(actual time=214.142..214.147 rows=20 loops=1)
Buffers: shared hit=13966 read=4832
-> Sort (cost=46004.16..46095.80 rows=36658 width=39)
(actual time=214.141..214.143 rows=20 loops=1)
Sort Key: o.total DESC
Sort Method: top-N heapsort Memory: 27kB
Buffers: shared hit=13966 read=4832
-> Hash Join (cost=1289.12..45028.70 rows=36658 width=39)
(actual time=7.805..205.935 rows=36609 loops=1)
Hash Cond: (o.customer_id = c.id)
Buffers: shared hit=13963 read=4832
-> Seq Scan on orders o (cost=0.00..43255.00 rows=184584
width=22)
(actual time=0.041..167.210 rows=181218 loops=1)
Filter: (created_at >= '2026-09-01 00:00:00+00'::
timestamp with time zone)
Rows Removed by Filter: 1818782
Buffers: shared hit=13423 read=4832
-> Hash (cost=1165.00..1165.00 rows=9930 width=33)
(actual time=7.684..7.684 rows=10000 loops=1)
Buckets: 16384 Batches: 1 Memory Usage: 830kB
Buffers: shared hit=540
-> Seq Scan on customers c (cost=0.00..1165.00
rows=9930 width=33)
(actual time=0.010..5.548 rows=10000 loops=1)
Filter: (country = 'DE'::text)
Rows Removed by Filter: 40000
Buffers: shared hit=540
Planning:
Buffers: shared hit=260
Planning Time: 2.135 ms
Execution Time: 214.430 ms02. Step 1: read the tree, innermost first
A plan is a tree printed with the first node at the top and children indented below. The arrows everyone quotes (->) point at child nodes. Nodes return rows to their parent, so execution starts at the deepest children and finishes at the root: here the two Seq Scan nodes run first, then the Hash, the Hash Join, the Sort, the Limit. Reading innermost-out tells you the order work actually happened in.
Every node carries two bracketed lines. The first, cost=0.00..43255.00, is the planner's estimate: units are arbitrary cost units, not milliseconds — the start-up cost before the first row, then the total. The second line, (actual time=... rows=... loops=...), is measurement: real milliseconds, real rows, and how many times the node ran. This plan has five node types, and each name is a sentence:
Seq Scan on orders— read every heap page ofordersand applyFilter: created_at >= ...to each row.Rows Removed by Filter: 1818782counts rows read and discarded: the scan's actual job was discarding 1.8 million rows to keep 181,218. ItsBuffers: shared hit=13423 read=4832lines count pages found in the cache versus fetched from the operating system — 18,255 page touches for one scan.Seq Scan on customers— the same, forcountry = 'DE': 10,000 rows kept, 40,000 discarded.Hash— build a hash table over the customers' ids, sized inBucketsandMemory Usage. It exists only to serve its parent.Hash Join— stream the orders side and probe the hash table per row, pairing each German order with its customer: 36,609 rows out.SortwithSort Method: top-N heapsort— keep only the 20 largest totals seen so far, in 27 kB of memory, instead of sorting 36,609 rows fully. TheLimitnode above it just stops after 20. A sort that does not fit inwork_mem(4 MB by default) printsSort Method: external merge Disk: …kBinstead: it spilled its rows to temporary files, which is much slower than an in-memory sort.
03. Step 2: compare estimates with reality, find the expensive node
Now the habit that makes plan reading diagnostic: compare the two bracketed lines on every node. Here the planner estimated 184,584 orders and got 181,218; estimated 9,930 German customers and got 10,000; estimated 36,658 joined rows and got 36,609. Those estimates came from the ANALYZE-collected statistics, and they are excellent — so the plan itself is sane. The query is slow because of what the plan does, not because the planner blundered: a quarter of a second, nearly all of it in the orders scan (actual time=0.041..167.210), whose buffers dwarf every other node. The most expensive node is the one whose actual time and Buffers dominate: the Seq Scan on orders.
When you do meet a wild estimate — expected 1 row, got 184,000 — distrust every decision above that node: join methods and memory grants were chosen for a different problem. Fresh or richer statistics usually fix it, and the statistics lab shows a live case.
One more line deserves attention: Planning Time: 2.135 ms against Execution Time: 214.430 ms. Planning cost is real, and the final lab records it per statement in pg_stat_statements. That works only because the lab container turns on pg_stat_statements.track_planning: the setting is off by default, and then the planning columns stay at zero. And note the node widths (width=39): wider rows mean more bytes copied through every node above, which is why SELECT * in a join is itself a plan tax.
04. Step 3: what the default parallel plan adds
Reset the setting (RESET max_parallel_workers_per_gather;) and run the same EXPLAIN again. Two extra node types appear at the top, and every per-worker number gains a multiplier:
Limit (cost=31569.16..31571.50 rows=20 width=39)
(actual time=135.993..141.705 rows=20 loops=1)
-> Gather Merge (cost=31569.16..35133.34 rows=30548 width=39)
(actual time=135.991..141.700 rows=20 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Sort (cost=30569.14..30607.32 rows=15274 width=39)
(actual time=131.611..131.614 rows=18 loops=3)
Sort Key: o.total DESC
Sort Method: top-N heapsort Memory: 27kB
Worker 0: Sort Method: top-N heapsort Memory: 27kB
Worker 1: Sort Method: top-N heapsort Memory: 27kB
-> Hash Join (cost=1289.12..30162.70 rows=15274 width=39)
(actual time=12.759..126.261 rows=12203 loops=3)
Hash Cond: (o.customer_id = c.id)
-> Parallel Seq Scan on orders o
(cost=0.00..28671.67 rows=76910 width=22)
(actual time=0.046..95.911 rows=60406 loops=3)
Filter: (created_at >= '2026-09-01 ...'::
timestamp with time zone)
Rows Removed by Filter: 606261
-> Hash (cost=1165.00..1165.00 rows=9930 width=33)
(actual time=12.227..12.228 rows=10000 loops=3)
Buckets: 16384 Batches: 1 Memory Usage: 830kB
-> Seq Scan on customers c
(cost=0.00..1165.00 rows=9930 width=33)
(actual time=0.031..8.912 rows=10000 loops=3)
Filter: (country = 'DE'::text)
Rows Removed by Filter: 40000
Planning Time: 2.198 ms
Execution Time: 142.007 msGather Merge is the leader process collecting each worker's pre-sorted output and merging. The crucial detail is loops=3 on the Hash Join and everything beneath it: leader plus two workers each ran those nodes, and the per-loop numbers are per loop. The parallel scan reports rows=60406 loops=3 — about 181,000 rows in total, matching the serial plan. Multiply before you judge: a node reading actual time=0.10..0.12 rows=1 loops=20000 is not a 0.12 ms node, it is a 2.4-second one. On a parallel node the product is the work of all processes added up, not wall-clock time, because the workers run at the same time. This multiplication habit matters most inside nested-loop joins, where the inner side runs once per outer row.
05. Step 4: change one thing and re-read
The diagnosis said: the cost is a sequential scan that discards 1.8 million rows. Test that theory by removing the need to read them:
CREATE INDEX orders_created_idx ON orders (created_at);
ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.email, o.id, o.total
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE c.country = 'DE'
AND o.created_at >= timestamptz '2026-09-01'
ORDER BY o.total DESC
LIMIT 20;Limit (cost=25386.18..25388.51 rows=20 width=39)
(actual time=111.735..117.321 rows=20 loops=1)
-> Gather Merge (cost=25386.18..28818.99 rows=29422 width=39)
Workers Planned: 2
Workers Launched: 2
-> Sort (cost=24386.16..24422.93 rows=14711 width=39)
(actual time=108.276..108.279 rows=16 loops=3)
Sort Key: o.total DESC
-> Hash Join (cost=4619.32..23994.70 rows=14711 width=39)
(actual time=21.865..103.484 rows=12203 loops=3)
Hash Cond: (o.customer_id = c.id)
-> Parallel Bitmap Heap Scan on orders o
(cost=3330.20..22511.12 rows=74074 width=22)
(actual time=13.839..79.071 rows=60406 loops=3)
Recheck Cond: (created_at >= '2026-09-01 ...'::
timestamp with time zone)
Heap Blocks: exact=6127
-> Bitmap Index Scan on orders_created_idx
(cost=0.00..3285.75 rows=177777 width=0)
(actual time=15.008..15.009 rows=181218 loops=1)
Index Cond: (created_at >= '2026-09-01 ...'::
timestamp with time zone)
-> Hash
-> Seq Scan on customers c
Filter: (country = 'DE'::text)
Rows Removed by Filter: 40000
Planning Time: 1.471 ms
Execution Time: 117.585 msThe scan of orders became a Bitmap Index Scan feeding a Parallel Bitmap Heap Scan: the index found 181,218 matching entries, and total time fell from about 142 ms to 118 ms on this machine. Do not read Heap Blocks: exact=6127 as "the heap read shrank to a third". In a parallel bitmap scan PostgreSQL 17 reports only the leader's share of the heap blocks; three processes split the work, and together they visited roughly 18,000 pages — nearly all 18,255 pages of the table. (Rerun with max_parallel_workers_per_gather = 0 and the same node reports exact=18255.) The reason is where the rows live: created_at was generated at random, unrelated to the order rows sit on disk, so the 181,218 matches — about ten per page — are spread over almost every page. SELECT correlation FROM pg_stats WHERE tablename = 'orders' AND attname = 'created_at' confirms it: a value near 0 (within ±0.01 on our runs; ANALYZE samples rows, so the exact figure varies) means an index range cannot cluster the I/O. The time fell modestly because the scan no longer evaluates the filter on 1.8 million rows, not because it reads fewer pages. Notice what did not change: the join is still a hash join and customers is still scanned, because 10,000 of 50,000 rows is 20% of that table — too broad a slice for an index to pay, exactly as the first lesson predicted. And the honest overall win is modest, because nine per cent of a two-million-row table is still 181,000 rows to fetch, join and rank. A plan you can read tells you when you are done and when the design itself — this query shape, this index — needs the workload-driven treatment of the next lesson.
06. Common plan-reading mistakes
07. Check your understanding
08. Apply it
Write three variations of the dashboard query — a different country, a tighter date range, and ORDER BY o.created_at DESC instead of o.total — and read each plan before looking at its time. Predict first: which node will dominate, will the join method change, how many rows will the orders filter remove? Then run with EXPLAIN (ANALYZE, BUFFERS) and score yourself. Keep the dataset: the whole index design lab runs on it.
09. Review prompt
Without looking back: name the five node types of the serial plan in execution order, and say in one sentence each what it did. Explain what loops does to the numbers on a parallel plan. Finally, describe how you would locate the most expensive node, using both the actual times and the buffers.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.