EXPLAIN and the planner
Being able to read a plan is the difference between guessing at performance and knowing. It is one skill, it takes an afternoon, and it lasts your whole career.
How to run it
EXPLAIN (ANALYZE, BUFFERS, VERBOSE, SETTINGS, FORMAT TEXT) SELECT ...;
| Option | Adds |
|---|---|
ANALYZE | Actually runs the query and reports real timings and row counts |
BUFFERS | Pages read from cache vs disk — often the real story |
VERBOSE | Output columns per node |
SETTINGS | Non-default planner settings in effect |
WAL | WAL generated (for write statements) |
On an UPDATE or DELETE the changes really happen. Wrap it:
BEGIN; EXPLAIN (ANALYZE) UPDATE …; ROLLBACK;
Reading a plan
Limit (cost=0.71..48.32 rows=20 width=64)
(actual time=0.041..0.196 rows=20 loops=1)
Buffers: shared hit=27
-> Nested Loop (cost=0.71..1204.55 rows=506 width=64)
(actual time=0.039..0.189 rows=20 loops=1)
Buffers: shared hit=27
-> Index Scan Backward using idx_order_cust_date on customer_order o
(cost=0.43..312.18 rows=506 width=48)
(actual time=0.021..0.048 rows=20 loops=1)
Index Cond: (customer_id = 42)
Buffers: shared hit=6
-> Index Scan using customer_pkey on customer c
(cost=0.28..1.76 rows=1 width=24)
(actual time=0.005..0.005 rows=1 loops=20)
Index Cond: (customer_id = 42)
Buffers: shared hit=21
Planning Time: 0.284 ms
Execution Time: 0.241 ms
- Read inside out, bottom upThe most indented nodes run first and feed their parents.
- Compare rows estimated with rows actual
rows=506vsrows=20. An order of magnitude apart is the single strongest signal of a problem. - Watch
loopsReportedactual timeis per loop. A node at 0.005 ms × 20,000 loops is 100 ms. - Check buffers
shared hitis cache;shared readis disk. Lots of reads on a hot query means the working set does not fit. - Ignore cost, use time
costis an arbitrary unit for comparing plans, not milliseconds.
Scan types
| Node | Means | Concerning when |
|---|---|---|
Seq Scan | Reads the whole table | On a large table with a selective filter |
Index Scan | Walks the index, fetches rows | Rarely — usually good |
Index Only Scan | Answered from the index alone | Ideal — unless Heap Fetches is high |
Bitmap Heap Scan | Collects row pointers, then reads pages in order | Normal for medium selectivity |
BitmapAnd/Or | Combines several indexes | Often a hint for a composite index |
A sequential scan is not automatically wrong. Reading 60% of a table sequentially is faster than 600,000 random index lookups, and the planner knows that.
Join types
| Join | Good when | Bad when |
|---|---|---|
Nested Loop | Outer side is small and inner side is indexed | Outer side is actually huge — the classic estimate failure |
Hash Join | Both sides large, equality join, fits in work_mem | It spills to disk (Batches > 1) |
Merge Join | Both inputs already sorted | An explicit sort of a large input is needed |
Six patterns behind most slow queries
1 · Row estimate is orders of magnitude wrong
-> Nested Loop (cost=… rows=1 …) (actual time=… rows=48213 loops=1)
The planner chose a nested loop believing one row would come back. Run
ANALYZE tablename;. If the estimate is still wrong on correlated columns,
create extended statistics:
CREATE STATISTICS stat_order_status_channel (dependencies, ndistinct) ON status, customer_id FROM customer_order; ANALYZE customer_order;
2 · A function around the indexed column
-- cannot use an index on placed_at
WHERE date_trunc('day', placed_at) = '2026-08-17'
-- can (a range on the raw column)
WHERE placed_at >= '2026-08-17' AND placed_at < '2026-08-18'
3 · Type mismatch in the predicate
Comparing a bigint column to a string literal, or text to
varchar with a different collation, can prevent index use. The plan shows a
cast in the Filter rather than an Index Cond.
4 · Sort spilling to disk
Sort Method: external merge Disk: 84920kB
Either raise work_mem for that session, or add an index that provides the
ordering so no sort is needed at all.
5 · Hash join batching
Buckets: 4096 Batches: 32 Memory Usage: 4097kB
Batches above 1 means the hash table did not fit and is being written to disk.
Raise work_mem, or reduce the number of rows reaching the join.
6 · Index-only scan with heap fetches
Index Only Scan using idx_order_lookup … Heap Fetches: 182304
The visibility map is stale, so PostgreSQL must check the table anyway.
VACUUM customer_order; and consider a more aggressive autovacuum threshold
for that table.
Statistics
SELECT attname, n_distinct, correlation,
most_common_vals, most_common_freqs
FROM pg_stats
WHERE tablename = 'customer_order' AND attname = 'status';
-- more detail for a skewed column
ALTER TABLE customer_order ALTER COLUMN status SET STATISTICS 500;
ANALYZE customer_order;
correlation near 1.0 means physical order matches logical order — which is
when a BRIN index becomes viable and index scans get cheaper.
Tools
- explain.dalibo.com and explain.depesz.com — paste a plan, get a visual tree with the expensive nodes highlighted.
auto_explain— logs the plan for any query exceeding a threshold, in production.pg_stat_statements— tells you which query to explain in the first place.
shared_preload_libraries = 'pg_stat_statements,auto_explain' auto_explain.log_min_duration = '500ms' auto_explain.log_analyze = on auto_explain.log_buffers = on auto_explain.log_nested_statements = on
A plan shows rows=1 estimated but rows=50000 actual on a Nested Loop. First thing to do?
A nested loop is a good choice for one row and a disaster for fifty thousand. The join type is a symptom; the cause is the estimate. Refresh statistics first, then consider extended statistics if the columns are correlated.