EXPLAIN shows the plan the PostgreSQL planner chose for a query, along with cost estimates — it does not run the query. EXPLAIN ANALYZE actually executes the statement and reports the real time and real row counts for every node. The single most useful skill is comparing the estimated rows against the actual rows: when they diverge by a large factor, the planner is working from bad statistics and is very likely choosing a slow plan for the wrong reason. This guide walks through running both commands and reading the plan tree from the bottom up.
What you’ll accomplish
- Run
EXPLAINandEXPLAIN ANALYZEand know which one to reach for. - Read a plan tree bottom-up and find the node that dominates the runtime.
- Spot a sequential scan on a large filtered table and confirm it with row counts.
- Recognize when estimated rows and actual rows disagree, and fix the statistics behind it.
- Tell the difference between a plan problem and an application problem you can’t fix by reading plans.
Prerequisites
- PostgreSQL 12 or newer. Modern versions default to parallel query, JIT on large plans, and extended statistics via
CREATE STATISTICS— all of which show up in plans and matter here. psql(or any client) with permission to run the query you want to analyze.- A table with enough rows that plan choices actually differ — a few hundred thousand rows minimum. On a 50-row table every plan looks the same and the exercise teaches you nothing.
Warning: EXPLAIN ANALYZE runs the statement. For a SELECT that is harmless, but EXPLAIN ANALYZE DELETE ... or EXPLAIN ANALYZE UPDATE ... will modify data. Wrap any write in a transaction you roll back:
BEGIN;
EXPLAIN ANALYZE DELETE FROM orders WHERE created_at < '2020-01-01';
ROLLBACK;
How it works
A query plan is a tree of nodes. Each node consumes rows from its children and passes rows up to its parent. You read it bottom-up and inside-out: the most deeply indented nodes run first, and the top node is the last thing to execute and produce the final result. In psql’s text output, deeper indentation and the -> marker mean “child of the node above.”
The node types you will meet most often:
- Seq Scan — read the whole table, row by row. Fine for small tables or when most rows match; a red flag on a large table with a selective filter.
- Index Scan — walk an index to find matching rows, then fetch each row from the heap.
- Index Only Scan — answer entirely from the index, no heap fetch, because every needed column is in the index and the page is visible.
- Bitmap Index Scan / Bitmap Heap Scan — build a bitmap of matching row locations from one or more indexes, then read the heap in physical order. Chosen when a filter matches too many rows for a plain index scan but too few for a seq scan.
- Nested Loop — for each row from the outer child, probe the inner child. Fast when the outer side is tiny; catastrophic when the planner expected 3 outer rows and there are 300,000.
- Hash Join — build a hash table from one side, probe it with the other. Good for joining two large-ish sets.
- Merge Join — both inputs arrive sorted; walk them in lockstep.
- Sort — order rows for
ORDER BY, a merge join, or aGROUP BY. Watch where it happens. - Aggregate / HashAggregate / GroupAggregate — compute
count,sum,GROUP BY, and similar.
Every node prints a cost line. cost=0.29..8.51 is startup_cost..total_cost in arbitrary planner units — startup is the cost before the first row is returned, total is the cost to return all rows. rows= is the planner’s estimate of how many rows the node emits; width= is the estimated average row size in bytes. Under EXPLAIN ANALYZE you also get actual time=0.012..3.400 rows=42 loops=1: real startup and total milliseconds, the real row count, and how many times the node ran. When loops is greater than 1 (typical on the inner side of a nested loop), the printed actual time and rows are per loop — multiply by loops to get the total work.
The core skill is reading rows= (estimate) against actual rows= and asking whether they agree. A node that estimates 5 rows but produces 50,000 is why the plan above it went wrong.
Step-by-step
Start with plain EXPLAIN to see the shape without paying to run it. For an expensive or destructive query, this is the safe first look.
EXPLAIN
SELECT o.id, o.total, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending';
Hash Join (cost=1234.00..45678.90 rows=5000 width=44)
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o (cost=0.00..40000.00 rows=5000 width=20)
Filter: (status = 'pending')
-> Hash (cost=900.00..900.00 rows=40000 width=32)
-> Seq Scan on customers c (cost=0.00..900.00 rows=40000 width=32)
Read it bottom-up: both tables are seq-scanned, customers is hashed, and the two feed a hash join. The orders seq scan has a Filter: (status = 'pending') and a total cost of 40000 — the dominant cost. That’s the node to interrogate.
Now run EXPLAIN ANALYZE with BUFFERS to get real numbers. BUFFERS reports how many pages came from cache versus disk — essential for judging whether a slow node is CPU-bound or IO-bound.
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, o.total, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending';
Hash Join (cost=1234.00..45678.90 rows=5000 width=44)
(actual time=12.004..820.551 rows=4981 loops=1)
Hash Cond: (o.customer_id = c.id)
Buffers: shared hit=128 read=22600
-> Seq Scan on orders o (cost=0.00..40000.00 rows=5000 width=20)
(actual time=0.021..790.204 rows=4981 loops=1)
Filter: (status = 'pending')
Rows Removed by Filter: 1995019
Buffers: shared read=22550
-> Hash (cost=900.00..900.00 rows=40000 width=32)
(actual time=11.400..11.401 rows=40000 loops=1)
-> Seq Scan on customers c (actual time=0.008..4.900 rows=40000 loops=1)
Planning Time: 0.240 ms
Execution Time: 821.900 ms
Read the top node’s total time. Execution Time: 821.900 ms is the whole query. The top Hash Join shows actual time=12.004..820.551 — its total (820.551 ms) is essentially the entire runtime, so the cost lives below it.
Find the most expensive node. The Seq Scan on orders has actual time=0.021..790.204 — almost all of the 820 ms. Look one line down: Rows Removed by Filter: 1995019. Postgres read two million rows to keep 4,981. That is a selective filter on a large table with no supporting index — the textbook seq-scan problem.
Check estimate versus actual. On the orders seq scan, rows=5000 (estimate) versus actual ... rows=4981 — those agree, so statistics are fine here; the problem is purely a missing index, not a bad estimate. (When they don’t agree, that’s your signal to run ANALYZE; see Troubleshooting.)
Add the index and re-run. The filter is on status, and only a small fraction of rows are pending, so a plain B-tree index (or a partial index on the hot value) will help.
CREATE INDEX CONCURRENTLY idx_orders_status ON orders (status);
Hash Join (cost=1150.00..3820.40 rows=4981 width=44)
(actual time=11.900..38.200 rows=4981 loops=1)
Hash Cond: (o.customer_id = c.id)
Buffers: shared hit=5210
-> Bitmap Heap Scan on orders o (actual time=0.640..21.100 rows=4981 loops=1)
Recheck Cond: (status = 'pending')
-> Bitmap Index Scan on idx_orders_status
(actual time=0.410..0.410 rows=4981 loops=1)
Index Cond: (status = 'pending')
Planning Time: 0.310 ms
Execution Time: 39.400 ms
The seq scan is gone. Postgres now does a Bitmap Index Scan to find the 4,981 matching rows and a Bitmap Heap Scan to fetch them, and Buffers shows all-cache hits and no read. Execution time dropped from 821 ms to 39 ms. If the filter had returned only a handful of rows, you’d see a plain Index Scan instead of the bitmap pair.
Keep FORMAT TEXT for reading; switch formats only when tooling needs it. EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) is the default and the most readable. FORMAT JSON is for feeding a visualizer; don’t read raw JSON by eye.
Validate it works
You know the change landed when three things are true in the new plan:
- The node type changed.
Seq Scanon the filtered table becameIndex Scan,Index Only Scan, or aBitmap Index Scan/Bitmap Heap Scanpair. - Actual time dropped at the top node — compare
Execution Timebefore and after. - Estimate matches actual. After you run
ANALYZE orders;, the node’srows=estimate should land close toactual ... rows=. A fresh statistics run is what lets the planner trust the index in the first place:
ANALYZE orders;
Run the EXPLAIN (ANALYZE, BUFFERS) twice and compare the second runs — the first execution warms the cache, so the second is the honest steady-state number.
Troubleshooting
-
Stale statistics — estimates are wrong across the board. After a bulk load, migration, or a table that autovacuum hasn’t reached,
rows=estimates are far off actual and the planner picks bad joins. Fix: runANALYZE <table>;(orVACUUM ANALYZE). This is the first thing to try whenever estimate and actual disagree by more than roughly 10x. -
Estimate wildly off because two columns are correlated. The planner assumes columns are independent. If
cityandpostal_codemove together, a filter on both makes it multiply two selectivities and estimate far too few rows — often triggering a nested loop that then runs millions of times. Fix with extended statistics:CREATE STATISTICS orders_city_zip (dependencies) ON city, postal_code FROM orders; ANALYZE orders; -
The planner ignores your index. Two common causes. First, the index isn’t selective enough — if
status = 'pending'matches 60% of rows, a seq scan genuinely is cheaper and Postgres is right. Second, a type mismatch: filtering abigintcolumn withWHERE id = '42'or wrapping the column in a function (WHERE lower(email) = ...) prevents a plain index from being used. Fix the cast, or build an expression index (CREATE INDEX ON users (lower(email))). -
ANALYZE timing skewed by cold cache. The first
EXPLAIN ANALYZEafter a restart reads from disk and looks terrible; the numbers say IO-bound when steady-state is CPU-bound. AddBUFFERS— a highread=versushit=confirms cold cache — and run the query a second time to get the warm number. -
Sort spilling to disk. A
Sortnode showingSort Method: external merge Disk: 148000kBis sorting on disk because the data didn’t fit inwork_mem. Disk sorts are slow. Raisework_memfor the session and re-check:SET work_mem = '256MB';If the sort then shows
Sort Method: quicksort Memory: ..., it stayed in RAM. Setwork_memper session or per role, not globally to a huge value — every connection and every sort node can allocate it.
When this is the wrong approach
Reading plans is the right tool when one query is slow and you can name it. It is the wrong tool for several problems that look like slow queries:
- N+1 from the application. If the app issues one fast query per row of a result set, each plan is perfect and the total is still slow. No amount of plan-reading fixes it — the fix is in the ORM or the query shape.
- Lock contention. A query that is fast alone but slow under load is often waiting on a lock, not on its plan. Check
pg_stat_activityforwait_event_type = 'Lock'. - Connection pool exhaustion. If queries queue because there are no free connections, they’re slow before the planner even sees them — see Postgres connection pool exhausted. Bloat from missing maintenance also degrades plans over time; see PostgreSQL VACUUM and autovacuum.
Before you EXPLAIN anything, find which query to look at. Enable pg_stat_statements and sort by total time — it tells you the query that actually costs your database the most, which is rarely the one you’d guess. The official references worth bookmarking are Using EXPLAIN and the EXPLAIN command reference.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.