Reading PostgreSQL EXPLAIN ANALYZE Execution Plans
Interpret PostgreSQL EXPLAIN (ANALYZE, BUFFERS) plans, spot sequential scans and row estimate skew, verify index selectivity, and diagnose slow joins.
On this page
Why Planner Estimates Lie Without ANALYZE and BUFFERS
When an API endpoint slows down under production load, running bare EXPLAIN SELECT ... shows only what the PostgreSQL query planner guessed would happen based on table histograms. If statistics are stale, columns are correlated (country = 'JP' AND currency = 'JPY'), or a parameterized query hides skewed tenant sizes, the planner’s estimated cost bears little relation to reality.
Adding (ANALYZE, BUFFERS) tells PostgreSQL to actually execute the statement and annotate every plan node with two sets of numbers: planner estimates (cost=... rows=... width=...) alongside observed runtime execution (actual time=... rows=... loops=...) and 8KB buffer page accounting (Buffers: shared hit=... read=...). Because EXPLAIN ANALYZE executes the statement for real, always wrap INSERT, UPDATE, or DELETE diagnostics inside BEGIN; EXPLAIN (ANALYZE, BUFFERS) ...; ROLLBACK; so test runs never mutate production records.
You can paste raw PostgreSQL text or JSON plans into the Interactive SQL EXPLAIN Analyzer to highlight expensive sequential scans, row estimation skew, and candidate index gaps automatically.
Reading the Execution Tree From Inside Out
PostgreSQL formats plans as an indented tree where child nodes feed rows upward to parent nodes. To understand runtime flow, read from the deepest indented leaf upward, paying close attention to three multipliers:
actual time=startup..totalandloops=N: Both startup time and total time on a node report the average per loop. When a child Index Scan showsactual time=0.04..0.12 rows=3 loops=15000, that leaf actually consumed0.12 * 15000 = 1,800 msacross 15,000 nested-loop iterations! Multiplyingtotal_time * loopscatches hidden N+1 join bottlenecks immediately.- Estimated
rowsvsactual rows: A node predictingrows=12while actually returningrows=184000tricks PostgreSQL into picking a Nested Loop join over a Hash Join, blowing up latency by two orders of magnitude. Rows Removed by Filter: When an Index Scan or Seq Scan reads 500,000 tuples from disk only to discard 499,850 of them viaFilter:, your index either covers only the leading column or omits a crucial selectivity predicate.
-- Diagnose a slow multi-tenant order listing query
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT o.id, o.total_cents, o.created_at
FROM orders o
WHERE o.tenant_id = 'tnt_9481'
AND o.status = 'pending'
ORDER BY o.created_at DESC
LIMIT 50;
Look at a typical problematic plan output before tuning:
Limit (cost=18420.11..18420.24 rows=50 width=32) (actual time=312.405..312.419 rows=50 loops=1)
Buffers: shared hit=1142 read=9830
-> Sort (cost=18420.11..18482.61 rows=25000 width=32) (actual time=312.401..312.408 rows=50 loops=1)
Sort Key: created_at DESC
Sort Method: top-N heapsort Memory: 31kB
Buffers: shared hit=1142 read=9830
-> Seq Scan on orders o (cost=0.00..17589.50 rows=25000 width=32) (actual time=0.118..298.711 rows=41200 loops=1)
Filter: ((tenant_id = 'tnt_9481'::text) AND (status = 'pending'::text))
Rows Removed by Filter: 958800
Buffers: shared hit=1142 read=9830
Planning Time: 0.245 ms
Execution Time: 312.580 ms
Notice the smoking guns: Seq Scan on orders touched 1,142 + 9,830 = 10,972 8KB pages (~85 MB of data), discarded 958,800 non-matching rows in Rows Removed by Filter, and then ran an in-memory Sort just to return 50 rows.
Fixing Scan Bottlenecks with Composite and Partial Indexes
Ordering columns correctly inside a B-tree composite index transforms both the filter and the ORDER BY ... LIMIT 50 step. Place equality predicates (tenant_id, status) first, followed by the sort/range column (created_at DESC). Better yet, if 95% of orders are historical 'completed' rows and dashboards query 'pending' orders almost exclusively, a partial index shrinks index storage dramatically so the entire B-tree stays resident in shared_buffers.
-- Composite partial index covering equality filters + sort order
CREATE INDEX CONCURRENTLY idx_orders_tenant_pending_created
ON orders (tenant_id, created_at DESC)
WHERE status = 'pending';
-- Refresh planner histograms before re-testing
ANALYZE orders;
Re-running EXPLAIN (ANALYZE, BUFFERS) after building the partial index switches the plan into a backward/forward Index Scan that reads only the exact 50 matching rows and eliminates the Sort node altogether (Buffers: shared hit=4, execution under 1 ms). Notice also CREATE INDEX CONCURRENTLY: in live production databases, omitting CONCURRENTLY acquires a SHARE lock that blocks all INSERT, UPDATE, and DELETE writes on orders until index creation completes.
Understanding Join Strategies and Bitmap Scans
When reading multi-table execution trees, recognize the three join algorithms PostgreSQL switches between based on estimated row counts and memory budgets:
- Nested Loop: Ideal when the outer input produces only a handful of rows (for example,
actual rows=10) and the inner table has a selective B-tree index on the join key. When row estimates under-predict an outer input of 50,000 rows asrows=5, a Nested Loop becomes catastrophic. - Hash Join: Builds an in-memory hash table of the smaller filtered table (
Hash) and probes it linearly across the larger stream. Watch forBatches: 16insideHashnodes, which means the hash table spilled out ofwork_memonto temporary disk files. - Merge Join: Zips two pre-sorted streams together efficiently for large equijoins, especially when an existing index already supplies both sides in matching sort order.
Similarly, do not confuse a Bitmap Heap Scan with a slow Seq Scan. When a predicate matches several thousand scattered rows (around 1% to 10% of a table), PostgreSQL builds an in-memory bitmap of page offsets from one or more Bitmap Index Scan nodes first, then reads each heap page sequentially in physical disk order, saving massive random I/O. Only when the bitmap turns lossy (Heap Blocks: exact=1024 lossy=42000) because work_mem overflowed does PostgreSQL have to re-check individual row conditions inside lossy pages.
Common Planner Skew Traps and Hidden Costs
Even after adding indexes, four subtle patterns continue to stall PostgreSQL queries:
- Non-sargable expressions on indexed columns: Writing
WHERE LOWER(email) = $1orWHERE created_at::date = '2026-11-24'prevents the planner from using a plain index onemailorcreated_at. Rewrite date comparisons as half-open intervals (created_at >= '2026-11-24' AND created_at < '2026-11-25') or build an expression index (ON users (LOWER(email))). - Temp disk spills in
SortorHash: WhenSort Method: external merge Disk: 48120kBappears,work_memwas too small for the sort set, forcing slow temporary disk I/O. Increasingwork_memper session (carefully, since each active sort node allocates up towork_mem) or tighteningWHEREselectivity eliminates the spill. - Correlated columns fooling single-column stats: PostgreSQL tracks column frequencies independently by default, severely underestimating or overestimating
WHERE make = 'Tesla' AND model = 'Model 3'. DefineCREATE STATISTICS ... (dependencies) ON make, model FROM vehiclesand runANALYZEso the planner models joint selectivity accurately. - Implicit type casts across bind parameters: Passing a
bigintparameter against anintegercolumn—or vice versa from an ORM—can silently disable index usage on older expressions or partition pruning. Match SQL parameter types explicitly.
Verifying Plan Improvements Before Merging Migrations
Before declaring a query optimization complete, inspect the FORMAT JSON or text plan in the Interactive SQL EXPLAIN Analyzer and verify four quantitative signals:
- Total
Buffers(shared hit + shared read) drops proportionally with the selectivity of yourLIMITorWHEREfilter, not the total table size. Rows Removed by Filterdrops near zero on high-frequency OLTP lookups.- No
Nested Loopmultiplies aloopscount into thousands over unindexed inner scans. actual rowsfalls within a 2x–5x factor of plannerrowsestimates afterANALYZE, proving the planner will keep choosing the fast plan as data grows.
FAQ
- What is the difference between EXPLAIN and EXPLAIN ANALYZE in PostgreSQL?
- Plain EXPLAIN only asks the query planner for cost and row guesses without executing the statement. EXPLAIN ANALYZE actually runs the query, so it reveals real wall-clock milliseconds, actual row counts, and loop counts—meaning writes must be wrapped in BEGIN ... ROLLBACK.
- Are Sequential Scans always bad in an EXPLAIN plan?
- No. On small tables under a few thousand rows, or when a query returns more than 10 to 20 percent of the table's pages, a sequential scan beats random index page hops. Focus on large sequential scans combined with heavy Rows Removed by Filter.
- Why does cost=0.00..450.20 look fast even when a query takes seconds?
- Planner cost units are arbitrary relative weights configured around seq_page_cost and random_page_cost, not milliseconds. Stale ANALYZE statistics or unindexed nested loops can make a 4-second query look cheap in estimated cost.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.