How to Read PostgreSQL Query Plans with EXPLAIN
Use EXPLAIN and EXPLAIN ANALYZE to find why a query is slow: read the plan tree, spot row-estimate errors, and know when an index is ignored.
On this page
Introduction
When a query is slow, guessing at the cause wastes time. PostgreSQL tells you exactly what it did if you ask with EXPLAIN. A query plan is a tree of operations, each annotated with estimated costs and, with ANALYZE, actual timing and row counts. Reading that tree turns a vague complaint about slowness into a specific diagnosis: a missing index, a bad row estimate, or a join strategy that scans too many rows.
This tutorial shows how to read a plan from the bottom up, how to compare estimated and actual rows to find where the planner misjudged, how to recognize the node types that dominate cost, and how to confirm a fix by re-running the plan. The examples use PostgreSQL, whose plan output is the model most relational databases follow even if the names differ.
Run EXPLAIN with the right options
Plain EXPLAIN shows only estimated costs without executing the query, which is useful for a risky query but hides the difference between an estimate and reality. EXPLAIN ANALYZE executes the query and reports actual times and rows, which is what you want when diagnosing an existing slowdown. Add BUFFERS to see how many shared blocks were read from cache versus disk, and add VERBOSE when you need to see the columns used in each node.
Wrap a slow query in EXPLAIN ANALYZE in a transaction you roll back if the query writes, and be aware that ANALYZE adds overhead that a hot production query might not tolerate. For a query that is slow but harmless to run, ANALYZE is the fastest route to the answer. For a destructive statement, use EXPLAIN alone or run it against a copy.
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT o.id, o.total, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending'
AND o.created_at >= now() - interval '7 days'
ORDER BY o.created_at DESC
LIMIT 50;
Read the plan bottom-up
A plan is printed as a tree with the root at the top, but execution flows from the leaves upward. Read the innermost indented nodes first, because they produce the rows that everything above consumes. Each node reports a cost range, estimated rows, and, with ANALYZE, actual rows and the time spent in that node and its children. The actual time of the root is the total query time, and the difference between a node’s time and its children’s times tells you where the cost is concentrated.
The key comparison is estimated rows against actual rows. A node that estimated ten rows but produced a hundred thousand has misled every decision above it, which is usually why the plan chose a slow strategy. Large estimate errors point at stale statistics, a correlation the planner does not know about, or a filter whose selectivity it cannot predict, such as an expression over a computed value.
Limit (cost=... rows=50) (actual time=... rows=50)
-> Sort (cost=... rows=...) (actual time=... rows=...)
Sort Key: o.created_at DESC
-> Nested Loop (cost=... rows=...) (actual time=... rows=...)
-> Index Scan on idx_orders_status_created (actual rows=...)
-> Index Scan on customers_pkey (actual rows=1 loops=...)
Buffers: shared hit=... read=...
Spot the node that dominates cost
A few node types account for most slow plans. A sequential scan over a large table with a selective filter means the index that should exist does not, or cannot be used. A nested loop with a high loop count means the outer side produced many rows and the inner side was probed once per row; a hash or merge join may be cheaper. A sort node that spills to disk, marked with a disk usage figure, means the sort exceeded work_mem and needs more memory or a different plan.
Buffers matter as much as time. A high read count in the buffers line means the query touched many blocks from disk; a high hit count means it read from cache. Repeatedly rereading the same blocks suggests an index is missing or a plan is rescanning a relation. Comparing buffers before and after a fix confirms whether the change reduced work, not just wall-clock time that may vary.
Seq Scan on orders o (cost=0.00..18542.00 rows=1200 width=32)
(actual time=0.02..210.55 rows=95000 loops=1)
Filter: ((status = 'pending') AND (created_at >= ...))
Rows Removed by Filter: 905000
Buffers: shared hit=1200 read=17342
-- estimated 1200 but actual 95000: stale statistics on status/created_at
Fix and confirm the plan changed
Once you identify the cause, apply the smallest fix that addresses it. A missing index on the filter or join columns is the most common. For estimate errors, run ANALYZE to refresh statistics, or increase the statistics target on the selective column so the planner samples more values and estimates better. For a sort spilling to disk, raise work_mem for that query rather than globally, since a global increase multiplies across connections.
Always re-run EXPLAIN ANALYZE after the fix and compare the actual rows, time, and buffers. A fix that changes the plan but not the actual rows processed has not solved the underlying problem. Record the before and after numbers so a future change that regresses the query can be caught, and consider a regression test that asserts the plan uses an expected index.
Test that the plan stays good
Plans are not stable contracts, because the planner adapts to data and statistics. Add a test that runs EXPLAIN on a critical query and asserts it does not contain a sequential scan on a large table, or that it uses a named index. Run it against a representative dataset so estimates resemble production. This catches the regression where a schema or statistics change silently flips a fast plan to a slow one.
psql -d app -c "EXPLAIN (ANALYZE, BUFFERS) SELECT ... " > before.txt
# apply fix (create index / ANALYZE / rewrite)
psql -d app -c "EXPLAIN (ANALYZE, BUFFERS) SELECT ... " > after.txt
diff before.txt after.txt # assert the scan/join strategy changed for the better
Common pitfalls
Reading only the top node and ignoring the tree, trusting estimated rows without checking actuals, adding an index blindly without confirming it is used, increasing work_mem globally to fix one sort, and assuming a sequential scan is always bad are the recurring mistakes. Reading bottom-up, comparing estimates to actuals, checking buffers, and re-running the plan after each change address them.
Conclusion
EXPLAIN turns query tuning from guesswork into reading. Run it with ANALYZE and BUFFERS, read the tree from the leaves up, compare estimated and actual rows to find where the planner misjudged, look for the node that dominates cost and buffers, then apply a targeted fix and confirm the plan changed. Self-check by re-running the plan after the fix and asserting the expensive node is gone or the index is now used. A plan is evidence, so read it before you change anything.
Sources: PostgreSQL: Using EXPLAIN, PostgreSQL: EXPLAIN command, PostgreSQL: Planner statistics.
FAQ
- Why does the planner ignore my index?
- Common causes are low selectivity — the filter matches too large a fraction of the table so a sequential scan is cheaper — stale or missing statistics, or a type mismatch that prevents the index from being used. Check the estimate errors and run ANALYZE before assuming the index is wrong.
- Is a sequential scan always bad?
- No. On a small table, or when the query must read most of the rows anyway, a sequential scan is the cheapest plan. A sequential scan is only a problem when it reads far more rows than the result contains.
Report a problem with this articleOpens a pre-filled issue on GitHub.