Part 16 / Stage 4
Reading query plans
Goal: See what the database actually does with your SQL — read EXPLAIN top to bottom, tell estimates from reality with ANALYZE and BUFFERS, recognise every scan type and join algorithm, and catch the planner working from bad statistics. Time: ~2.5 hours
What you will learn
EXPLAIN: plan nodes, costs, estimated rowsEXPLAIN ANALYZE(andBUFFERS): actual rows, actual time, cache hits- Scan types: sequential, index, index-only, bitmap
- Join algorithms: nested loop, hash join, merge join
- Spotting bad estimates, and
CREATE STATISTICSfor correlated columns
The lab table for this part — 200,000 orders, built in seconds:
CREATE TABLE big_orders AS
SELECT g AS id, (g % 5000) + 1 AS customer_id,
DATE '2024-01-01' + (g % 365) AS order_date,
round((random() * 500)::numeric, 2) AS amount
FROM generate_series(1, 200000) AS g;
ANALYZE big_orders;
SELECT 200000
ANALYZE
(ANALYZE immediately — Part 15's rule: never let the planner meet a big table it has no statistics for.)
Topics in this part
Practice
SQL workbench — write and run queries here
Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.
These build their own lab tables (re-runnable solutions); run them in any scratch database. Predict every plan before you EXPLAIN it — the prediction is the exercise.
Exercise 1: Predict the scan
What to do: On a fresh 200k-row big_orders: (a) EXPLAIN ANALYZE one day's orders with no index — name the scan and the smell; (b) index order_date and re-ask — name the new shape; (c) ask for eleven months — why is it a Seq Scan again, and why is that correct?
Sample output (the shapes):
Seq Scan on big_orders (actual rows=548 loops=1)
Bitmap Heap Scan on big_orders (actual rows=548 loops=1)
-> Bitmap Index Scan on idx_big_orders_date (actual rows=548 loops=1)
Seq Scan on big_orders
💡 Hint: 548 rows out of 200,000 is bitmap territory; at roughly 92% of the table, sequential is the fast plan, not a failure.
Show the solution to Exercise 1
-- Exercise 1: Predict the scan (re-runnable)
DROP TABLE IF EXISTS big_orders;
CREATE TABLE big_orders AS
SELECT g AS id, (g % 5000) + 1 AS customer_id,
DATE '2024-01-01' + (g % 365) AS order_date,
round((random() * 500)::numeric, 2) AS amount
FROM generate_series(1, 200000) AS g;
ANALYZE big_orders;
-- (a) One day of orders, no index: Seq Scan, huge Rows Removed.
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM big_orders WHERE order_date = DATE '2024-03-01';
-- (b) Index it: the same query becomes a bitmap scan.
CREATE INDEX idx_big_orders_date ON big_orders (order_date);
ANALYZE big_orders;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM big_orders WHERE order_date = DATE '2024-03-01';
-- (c) Most of the table: the planner rightly returns to Seq Scan.
EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE order_date >= DATE '2024-02-01';
Exercise 2: Diagnose a write without doing it
What to do: EXPLAIN ANALYZE the deletion of customer 42's orders — without losing them. Prove afterwards they survived.
Sample output (the proof):
still_there
-------------
40
(1 row)
💡 Hint: BEGIN, then EXPLAIN (ANALYZE) the DELETE, then ROLLBACK. The plan shows real actual-rows; the data stays.
Show the solution to Exercise 2
-- Exercise 2: Diagnose a write without doing it
BEGIN;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
DELETE FROM big_orders WHERE customer_id = 42;
ROLLBACK;
-- The plan ran for real (actual rows shown) and the rollback kept the rows.
SELECT count(*) AS still_there FROM big_orders WHERE customer_id = 42;
Exercise 3: Name that join
What to do: With big_orders (indexed on customer_id) and a 5,000-row dim_customers: predict, then confirm, the join algorithm for (a) the full aggregate join and (b) the one-customer lookup. Explain each choice in one sentence.
💡 Hint: (a) lots against lots calls for a Hash Join, hashing the small side; (b) one outer row against an indexed inner calls for a Nested Loop.
Show the solution to Exercise 3
-- Exercise 3: Name that join (re-runnable; needs ex01's table)
DROP TABLE IF EXISTS dim_customers;
CREATE TABLE dim_customers AS
SELECT g AS customer_id, 'Customer ' || g AS name FROM generate_series(1, 5000) g;
ALTER TABLE dim_customers ADD PRIMARY KEY (customer_id);
CREATE INDEX IF NOT EXISTS idx_big_orders_customer ON big_orders (customer_id);
ANALYZE dim_customers;
-- (a) lots x lots -> Hash Join:
EXPLAIN (COSTS OFF)
SELECT d.name, count(*) FROM big_orders b
JOIN dim_customers d ON d.customer_id = b.customer_id GROUP BY d.name;
-- (b) one outer row probing an index -> Nested Loop:
EXPLAIN (COSTS OFF)
SELECT b.* FROM big_orders b
JOIN dim_customers d ON d.customer_id = b.customer_id
WHERE d.name = 'Customer 42';
Exercise 4: Found the lie, fixed the stats
What to do: Rebuild the correlated addresses table (city determines pin). Show the estimate-vs-actual gap on the Pune + 411001 filter, then close it with CREATE STATISTICS ... (dependencies) and a fresh ANALYZE. Quote your before/after rows= numbers.
💡 Hint: before: estimate ≈ ¼ × ¼ of the table; after: within a whisker of 25,000. The gap, not the scan type, was the finding.
Show the solution to Exercise 4
-- Exercise 4: The correlated-columns bug, found and fixed (re-runnable)
DROP TABLE IF EXISTS addresses;
CREATE TABLE addresses AS
SELECT g AS id,
CASE WHEN g % 4 = 0 THEN 'Pune' WHEN g % 4 = 1 THEN 'Delhi'
WHEN g % 4 = 2 THEN 'Chennai' ELSE 'Mumbai' END AS city,
CASE WHEN g % 4 = 0 THEN '411001' WHEN g % 4 = 1 THEN '110001'
WHEN g % 4 = 2 THEN '600001' ELSE '400001' END AS pin
FROM generate_series(1, 100000) AS g;
ANALYZE addresses;
-- Estimate ~6k vs actual 25k (rows= vs actual rows=):
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM addresses WHERE city = 'Pune' AND pin = '411001';
-- Teach the dependency, re-ANALYZE, re-read — estimate lands within ~1%:
CREATE STATISTICS addr_city_pin (dependencies) ON city, pin FROM addresses;
ANALYZE addresses;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM addresses WHERE city = 'Pune' AND pin = '411001';
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| EXPLAIN ANALYZE on a write, bare | The write happens | BEGIN ... ROLLBACK around it |
| Reading costs as milliseconds | Chasing abstract units | Costs compare plans; ANALYZE times reality |
| "Seq scan = bad" | Pointless indexes on fetch-most queries | Seq is optimal for big fractions; judge by Rows Removed |
| Ignoring estimate-vs-actual gaps | Fixing symptoms (the join) not cause (the stats) | Compare rows= to actual rows= first |
| enable_* flags in production | Planner fighting its own cost model forever | Diagnostic only, SET LOCAL in a transaction |
| Forgetting loops= | "actual rows=1" × 10,000 loops misread | Total work = rows × loops |
Quick recap
- EXPLAIN shows the plan, ANALYZE runs it and shows the actuals, BUFFERS separates cache hits from disk reads, and writes get wrapped in a ROLLBACK.
- Every node reads the same way: a start..total cost, an estimated row count taken from pg_stats, and the actuals right beside it.
- Scans ladder by selectivity from index scan through bitmap to sequential, and an index-only scan appears when the index plus the visibility map can answer alone.
- Nested loop joins suit a tiny outer with an indexed inner, hash joins suit lots against lots, and merge joins walk two sorted inputs in lockstep.
- A gap between estimated and actual rows is a root cause, and the fixes are ANALYZE, CREATE STATISTICS for dependent columns, and higher statistics targets.
Checklist
Before Part 17, make sure you can:
- Read a two-node plan aloud, innermost first, with its estimates.
- Explain Rows Removed by Filter and what it hints.
- Name the four scan types and each one's selectivity home.
- Say which join algorithm you'd expect for three given shapes.
- Demonstrate the correlated-columns estimate bug and its CREATE STATISTICS fix.
Read more: the official EXPLAIN usage chapter and planner statistics chapter.