Chapter 05

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.

⏱ 18 min readLevel: intermediate → advancedCore chapter

How to run it

the only invocation you need
EXPLAIN (ANALYZE, BUFFERS, VERBOSE, SETTINGS, FORMAT TEXT)
SELECT ...;
OptionAdds
ANALYZEActually runs the query and reports real timings and row counts
BUFFERSPages read from cache vs disk — often the real story
VERBOSEOutput columns per node
SETTINGSNon-default planner settings in effect
WALWAL generated (for write statements)
ANALYZE executes the statement

On an UPDATE or DELETE the changes really happen. Wrap it: BEGIN; EXPLAIN (ANALYZE) UPDATE …; ROLLBACK;

Reading a plan

a healthy 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
  1. Read inside out, bottom upThe most indented nodes run first and feed their parents.
  2. Compare rows estimated with rows actualrows=506 vs rows=20. An order of magnitude apart is the single strongest signal of a problem.
  3. Watch loopsReported actual time is per loop. A node at 0.005 ms × 20,000 loops is 100 ms.
  4. Check buffersshared hit is cache; shared read is disk. Lots of reads on a hot query means the working set does not fit.
  5. Ignore cost, use timecost is an arbitrary unit for comparing plans, not milliseconds.

Scan types

NodeMeansConcerning when
Seq ScanReads the whole tableOn a large table with a selective filter
Index ScanWalks the index, fetches rowsRarely — usually good
Index Only ScanAnswered from the index aloneIdeal — unless Heap Fetches is high
Bitmap Heap ScanCollects row pointers, then reads pages in orderNormal for medium selectivity
BitmapAnd/OrCombines several indexesOften 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

JoinGood whenBad when
Nested LoopOuter side is small and inner side is indexedOuter side is actually huge — the classic estimate failure
Hash JoinBoth sides large, equality join, fits in work_memIt spills to disk (Batches > 1)
Merge JoinBoth inputs already sortedAn 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

what the planner knows
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.
postgresql.conf
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.