Reading EXPLAIN & EXPLAIN ANALYZE
Spot sequential scans, bad estimates and expensive joins in a plan.
By Invicly Tech, , in SQL & PostgreSQL. About 11 minutes to read.
In short
EXPLAIN shows the plan Postgres chose for a query: a tree of scan and join steps with cost estimates. EXPLAIN ANALYZE actually runs it and adds real row counts and timings, revealing where time goes.
Explained simply
When you send a query, Postgres does not just run it. First the planner thinks of many ways to get the answer: which table to read first, whether to use an index, how to join. It estimates the cost of each way and picks the cheapest. EXPLAIN shows you the plan it picked.
The plan is a tree of steps called nodes. Each node does one job, such as reading a table, joining two inputs or sorting, and passes its rows up to its parent. The top node gives the final result to you.
Plain EXPLAIN only shows guesses. EXPLAIN ANALYZE really runs the query and adds what actually happened: how many rows each step produced and how long it took. Comparing the guesses with reality is the key skill, because most bad plans come from bad guesses.
Be careful: because EXPLAIN ANALYZE really runs the query, an UPDATE or DELETE will really change data. Wrap those in BEGIN and ROLLBACK.
Press Play on a diagram to walk through it one step at a time.
- Seq Scan on orders
- Filter: status = 'paid'
- Outer input, streamed
- Hash
- Built from Seq Scan on customers
- Inner input, loaded first
- 1Run with ANALYZE, BUFFERS
Real times, rows and pages read
- 2Start at the deepest nodes
Children run first and feed parents
- 3Compare rows
Estimated vs actual: big gaps mean bad stats
- 4Find the slow node
Largest actual time times loops
- 5Fix & re-run
Index, rewrite, or ANALYZE the table
- Seq Scan, many Rows Removed by Filter
- Missing or unusable index
- Estimate far from actual
- Stale stats: ANALYZE
- Correlated columns: CREATE STATISTICS
- Nested Loop with huge loops
- Bad estimate below it
- Missing index on inner side
- Sort Method: external merge Disk
- Raise work_mem for this query
- Or an index that gives the order
- Hash Batches greater than 1
- Hash spilled to disk
- More work_mem or fewer rows
In depth
Decoding one plan line
A typical line looks like this: Index Scan using orders_pkey on orders (cost=0.43..8.45 rows=1 width=64) (actual time=0.020..0.021 rows=1 loops=1).
The first bracket is the estimate. cost=0.43..8.45 means start-up cost (before the first row) and total cost, in arbitrary planner units where reading one page in order costs 1.0; they are not milliseconds. rows=1 is the estimated number of rows this node returns, and width=64 the average row size in bytes.
The second bracket comes from ANALYZE. actual time is in milliseconds, first row then last row, per loop. rows is the real row count, averaged per loop, and loops is how many times the node ran. For the inner side of a nested loop, multiply time and rows by loops to get the real total.
At the bottom, Planning Time and Execution Time give the totals for the whole statement.
- cost = startup..total, in planner units
- rows/width = estimated rows and bytes per row
- actual time is per loop, in ms
- Node total = actual time x loops
Scan and join nodes you will meet
Scans read a table: Seq Scan reads every page; Index Scan follows an index and fetches rows; Index Only Scan answers from the index; Bitmap Index Scan plus Bitmap Heap Scan collect matches first, then read pages in order. A line Rows Removed by Filter tells you how much work was thrown away.
Joins combine two inputs. Nested Loop runs the inner side once per outer row; great when the outer side is small and the inner side has an index, terrible when both are large. Hash Join builds a hash table from the smaller input, then streams the other one past it; good for large unsorted inputs. Merge Join walks two inputs already sorted on the join key.
Other common nodes: Sort (watch for Sort Method: external merge Disk, meaning it spilled to disk), HashAggregate and GroupAggregate for GROUP BY, Limit, Gather for parallel workers, and Memoize (PostgreSQL 14+), which caches inner lookups in a nested loop.
- For each outer row, probe inner
- Small outer + indexed inner
- No setup cost
- Slow if both sides are big
- Build hash on smaller input
- Stream the larger past it
- Equality joins only
- Needs work_mem; may spill to disk
- Both inputs sorted on the key
- Walk them side by side
- Great with indexes on both keys
- Sorting first can be costly
Estimated vs actual rows: finding the real problem
The planner picks join types and orders from its row estimates. If it expects 10 rows and gets 200,000, it may choose a nested loop that runs 200,000 times. So scan each node and compare rows in the estimate with rows in actual. A gap of 10 times or more is worth investigating, and the lowest node with a big gap is usually the cause.
Estimates come from statistics that ANALYZE collects: a sample of each column with its most common values, a histogram and the number of distinct values (see the pg_stats view). They go stale after big loads; autovacuum re-analyses eventually, but run ANALYZE yourself after bulk changes.
Two classic causes beyond stale stats: correlated columns (city = 'Paris' AND country = 'FR' is estimated as if independent; fix with CREATE STATISTICS) and skewed data that needs a bigger sample (ALTER TABLE ... ALTER COLUMN ... SET STATISTICS 500).
- Gap of 10x or more: suspect the estimate
- ANALYZE table after bulk loads
- CREATE STATISTICS for correlated columns
- SET STATISTICS raises the sample for one column
BUFFERS, settings and tools that help
Add BUFFERS to see I/O: shared hit is pages found in Postgres's cache, shared read is pages fetched from the operating system or disk, and temp read/written means data spilled to temporary files. Since PostgreSQL 18, EXPLAIN ANALYZE includes buffer counts by default. Timings change between a cold and a warm cache, so run a query two or three times and compare buffers as well as milliseconds.
Other useful options: VERBOSE shows output columns, SETTINGS lists non-default planner settings, and FORMAT JSON produces machine-readable output for visualisers such as explain.depesz.com or explain.dalibo.com, which colour the slowest nodes.
In production you usually cannot rerun the slow query by hand. The auto_explain module logs the plans of statements that take longer than auto_explain.log_min_duration, so you can read the plan of the exact slow run later.
- 1shared_buffers
Postgres cache: counted as shared hit
- 2OS page cache
Counted as shared read, but still fast
- 3Disk or network storage
Also shared read; slowest
- 4Temp files
Sorts and hashes larger than work_mem
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Run EXPLAIN and EXPLAIN ANALYZE~1h
- 2Read scan and join node types~1h
- 3Compare estimated and actual rows~1h
- 4Find the most expensive plan node~1h
Key points
- Seq Scan reads the whole table; fine for small tables, costly for big filtered ones.
- Cost numbers are relative estimates, not milliseconds.
- actual time is per loop; multiply by loops for the node's total.
- Wildly wrong row estimates often mean stale statistics; run ANALYZE.
Key terms
Tap a card to flip it. 0/5 known
Examples
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.name, SUM(o.total) AS total
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'paid'
GROUP BY c.name
ORDER BY total DESC;
-- Safely analyse a write: it really runs, so roll it back
BEGIN;
EXPLAIN ANALYZE UPDATE orders SET status = 'void' WHERE id = 1;
ROLLBACK;Spotting a stale-statistics problem
A nightly job loaded 2 million new events, and a dashboard query became slow. Step 1: EXPLAIN ANALYZE shows Index Scan on events (rows=120) (actual rows=1980000). The planner thinks the filter matches 120 rows, so it chose a nested loop over them. Step 2: run ANALYZE events to refresh the statistics. Step 3: rerun the plan; the estimate is now close to 2 million and the planner switches to a Hash Join, and the query drops from 40 seconds to 2.
EXPLAIN (ANALYZE, BUFFERS)
SELECT u.country, count(*)
FROM events e JOIN users u ON u.id = e.user_id
WHERE e.created_at >= current_date
GROUP BY u.country;
-- check when the table was last analysed
SELECT relname, last_analyze, last_autoanalyze, n_mod_since_analyze
FROM pg_stat_user_tables WHERE relname = 'events';
ANALYZE events;Fixing a sort that spills to disk
A report sorts 3 million rows and the plan shows Sort Method: external merge Disk: 180000kB. The sort did not fit in work_mem (default 4MB), so it wrote temp files. Step 1: raise work_mem for this session only and rerun. Step 2: the plan now says quicksort Memory, and the time drops. Step 3: if the query runs often, a better fix is an index that already delivers rows in that order, or a LIMIT so less data is sorted.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders ORDER BY total DESC;
-- Sort Method: external merge Disk: 180000kB
SET work_mem = '256MB'; -- this session only
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders ORDER BY total DESC;
-- Sort Method: quicksort Memory: ...
RESET work_mem;Quick reference
- EXPLAIN (ANALYZE, BUFFERS) query; real rows, times and page reads
- BEGIN; EXPLAIN ANALYZE DELETE ...; ROLLBACK; analyse writes safely
- cost is in planner units, not ms; actual time is ms per loop
- Estimated vs actual rows off by 10x or more: run ANALYZE or add statistics
- Sort Method: external merge Disk means the sort spilled; check work_mem
- EXPLAIN (FORMAT JSON) output pastes into explain.dalibo.com or explain.depesz.com
- auto_explain logs plans of slow statements automatically
Common mistakes
- Running EXPLAIN ANALYZE on DELETE or UPDATE outside a transaction — it really executes.
- Treating cost units as milliseconds.
- Tuning on a tiny dev database whose plans differ from production.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Run EXPLAIN and then EXPLAIN ANALYZE on SELECT count(*) FROM orders WHERE status = 'paid'. Write down the estimated rows and actual rows of the scan node.
- Exercise 2medium
Safely measure how long DELETE FROM sessions WHERE expires_at < now() - interval '30 days' would take, without deleting anything.
- Exercise 3hard
WHERE city = 'Paris' AND country = 'FR' is estimated at 40 rows but returns 9,000. Explain why and fix the estimate.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is EXPLAIN ANALYZE safe to run in production?
- For SELECT it is as safe as running the query, which may be heavy. For INSERT, UPDATE and DELETE it really changes data, so wrap it in BEGIN and ROLLBACK.
- Why is the plan different on my laptop and in production?
- Plans depend on table sizes, statistics and settings. A tiny dev table is often cheapest to Seq Scan, so test with realistic data volumes.
- What is a good tool to visualise EXPLAIN output?
- Paste the text or JSON plan into explain.depesz.com or explain.dalibo.com. pgAdmin also has a graphical explain view.
- Can I force Postgres to use my index?
- There are no built-in query hints. For testing you can SET enable_seqscan = off in one session, but the real fix is better statistics, a better index or a rewritten query.