CS › Database

Reading PostgreSQL EXPLAIN ANALYZE execution plans

How to read PostgreSQL 15 EXPLAIN (ANALYZE, BUFFERS) output, understand scan and join nodes, and fix planner row-count misestimates with table stats.

Reading PostgreSQL EXPLAIN ANALYZE execution plans

Before adding an index to a slow query, you need to know what the execution plan is actually telling you. This post explains how to read PostgreSQL EXPLAIN (ANALYZE, BUFFERS) metrics, how the planner picks scan and join nodes, and how to fix stale statistics when estimates drift.

Tested with PostgreSQL 15.4. In PostgreSQL 15, ANALYZE doesn’t enable BUFFERS automatically, so always write EXPLAIN (ANALYZE, BUFFERS) explicitly.

Background

A bulletin board list API in one of my side projects crossed 100,000 rows and suddenly took nearly a full second per request. I ran EXPLAIN, stared at cost=0.00..1834.00, and realized I couldn’t explain what those numbers meant or why PostgreSQL kept picking a Seq Scan even when an index existed. I sat down with the “Using EXPLAIN” chapter of the PostgreSQL documentation, generated test tables locally, and watched how each node changed as I adjusted indexes and statistics.

How the planner builds and scores a plan

A PostgreSQL execution plan is a tree. Deeply indented child nodes execute first and pass rows upward to their parent nodes. Every node reports two sets of numbers:

  • cost=startup..total rows=estimated width=avg_bytes: The planner’s estimate derived from table statistics. Cost units are relative to seq_page_cost (default 1.0), not milliseconds.
  • actual time=first_row_ms..last_row_ms rows=actual loops=iterations: The measured result from actually running the query via ANALYZE. Both actual time and rows are averages per loop, so multiply them by loops to get the node’s real total work.
  • Buffers: shared hit=a read=b: Pages served from PostgreSQL’s shared buffers (hit) versus pages fetched from the OS page cache or disk (read).

The planner reads column statistics stored in pg_statistic (exposed through the pg_stats view), estimates how many rows each predicate will return, scores candidate plans, and runs the cheapest one.

flowchart TD
    A["ANALYZE samples table rows"] --> B["Store column stats in pg_stats"]
    B --> C["Planner estimates row counts"]
    C --> D["Compare cost of candidate plans"]
    D --> E["Execute lowest-cost plan"]
    E --> F["Compare estimated vs actual rows"]

Because every cost calculation starts from row-count estimates, most bad plans trace back to a row-count misestimate rather than a broken cost model. If the planner expects 1 row and the query actually returns 50,000, it happily chooses a Nested Loop join—and repeats the inner index scan 50,000 times.

Scan and join node selection

PostgreSQL picks a scan node based on what fraction of the table the query needs to read:

Scan nodeWhen the planner picks itKey metric to inspect
Seq ScanSmall tables or reading a large share of rowsRows Removed by Filter
Index ScanFetching a small slice of rows in index orderIndex Cond
Index Only ScanEvery selected column lives in the indexHeap Fetches (closer to 0 is better)
Bitmap Heap ScanMedium row fractions, or combining multiple indexes (OR/AND)Recheck Cond, Heap Blocks: exact/lossy

Join nodes depend on input sizes and whether the inputs are already sorted:

Join nodeBest suited forWatch out for
Nested LoopSmall outer input with an indexed inner tableCatastrophic slowdown if outer row estimate is too low
Hash JoinEquality joins when one side fits in work_memBatches > 1 means the hash table spilled to disk
Merge JoinBoth inputs are already sorted on the join keyExtra Sort steps erase the advantage

When not to run EXPLAIN ANALYZE: Unlike plain EXPLAIN, EXPLAIN ANALYZE actually executes the statement. If you’re inspecting an UPDATE or DELETE, always wrap it in BEGIN; EXPLAIN (ANALYZE, BUFFERS) ...; ROLLBACK; so you don’t mutate data by accident. On a busy production primary, running ANALYZE on a query that takes tens of seconds adds real load—inspect the estimated plan with plain EXPLAIN first, and run ANALYZE against a read replica whenever possible. Also keep in mind that per-node timing overhead can inflate actual time slightly compared to uninstrumented execution.

Diagnosing a slow query and fixing stale stats

Here is the bulletin board list query before optimization, trimmed to the key lines of EXPLAIN (ANALYZE, BUFFERS):

1
2
3
4
5
6
EXPLAIN (ANALYZE, BUFFERS)
SELECT p.id, p.title, u.nickname
FROM post p JOIN users u ON u.id = p.user_id
WHERE p.board_id = 3
ORDER BY p.created_at DESC
LIMIT 20;
1
2
3
4
5
6
7
8
9
Limit  (cost=4120.55..4120.60 rows=20 width=52) (actual time=812.4..812.4 rows=20 loops=1)
  Buffers: shared hit=1204 read=7310
  ->  Sort  (cost=4120.55..4170.55 rows=20000 width=52) (actual time=812.4..812.4 rows=20 loops=1)
        Sort Key: p.created_at DESC
        Sort Method: top-N heapsort  Memory: 30kB
        ->  Hash Join  (actual time=3.1..790.2 rows=33412 loops=1)
              ->  Seq Scan on post p  (actual time=0.0..760.8 rows=33412 loops=1)
                    Filter: (board_id = 3)
                    Rows Removed by Filter: 66588

Reading from the inside out makes the bottleneck obvious: Seq Scan read all 100,000 rows, threw away 66,588 of them, joined the remaining 33,412 rows, and sorted them just to return 20. The read=7310 counter shows how many pages missed PostgreSQL’s shared buffers. After I added a composite index on (board_id, created_at), the plan flipped to Limit -> Nested Loop -> Index Scan Backward using idx_post_board_created, buffer usage dropped to shared hit=64, and execution time fell from 812ms to 0.3ms. I explained why (board_id, created_at) beats the reverse order in B-Tree index internals and composite index column order.

When a node’s estimated rows and actual rows are off by an order of magnitude or more, check table statistics before touching indexes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
-- Check when statistics were last collected
SELECT relname, last_analyze, last_autoanalyze, n_live_tup, n_mod_since_analyze
FROM pg_stat_user_tables WHERE relname = 'post';

-- Inspect column distribution stats
SELECT attname, n_distinct, most_common_vals, correlation
FROM pg_stats WHERE tablename = 'post' AND attname = 'board_id';

-- Increase sample target and refresh statistics
ALTER TABLE post ALTER COLUMN board_id SET STATISTICS 1000;
ANALYZE post;

-- Capture correlated columns with extended statistics
CREATE STATISTICS st_post_board_status (dependencies) ON board_id, status FROM post;
ANALYZE post;

Production pitfalls and checklist

Right after a bulk INSERT or data migration, autovacuum hasn’t run ANALYZE yet, so table statistics are empty or severely stale. In that window, row estimates can be off by thousands of times and lure the planner into a slow Nested Loop. Always end migration scripts with an explicit ANALYZE. Also remember that prepared statements with bind parameters can switch from a custom plan to a generic plan after several executions, so a plan tested with hardcoded constants in psql may differ from what your application runs.

Read execution plans from the deepest node upward, and check for gaps between estimated and actual rows first. I use this five-point checklist every time I tune a query:

  • Did you run EXPLAIN (ANALYZE, BUFFERS) so buffer hits and reads are visible?
  • Does any node have a 10x or larger gap between estimated rows and actual rows?
  • Did you multiply actual time and rows by loops to spot the real bottleneck?
  • Did you check waste indicators like Rows Removed by Filter, Heap Fetches, and Hash Join Batches?
  • Were write queries wrapped in BEGIN ... ROLLBACK?
This post is licensed under CC BY 4.0 by the author.