Reading Query Plans with EXPLAIN and ANALYZE
A query plan is the database telling you exactly how it intends to answer your question â before or after it actually runs.
- Cost units â why the planner's numbers are relative, not milliseconds
- Actual vs estimated rows â the single most important comparison in any plan
- Join strategies â nested loop, hash join, and merge join, and when each wins
- A tuning loop â measure, change one thing, measure again Once you can read a plan, performance work stops being guesswork.
Prerequisites
- !Basic SELECT, WHERE, and JOIN syntax
- !What indexes are and how B-tree indexes work
- !The difference between a clustered and non-clustered index (helpful, not required)
What You'll Learn
- 1Explain what the planner's cost numbers actually represent
- 2Run EXPLAIN (ANALYZE, BUFFERS) and interpret every major line
- 3Spot row-estimate blowups, useless indexes, and bad join choices
- 4Apply a repeatable loop for diagnosing and fixing slow queries
The Planner in 60 Seconds
Before PostgreSQL runs your query it builds a plan: a tree of operations such as sequential scans, index scans, joins, sorts, and aggregates. The planner estimates the cost of every candidate plan using statistics about your tables â row counts, value distributions, correlation between columns â and picks the cheapest estimated plan. Cost units are arbitrary and relative: a cost of 1,000 in one plan means something only when compared with another plan's cost for the same query. Milliseconds appear only when you run the plan and measure it.
This split between estimated and actual is the key to everything that follows. If the planner believes a filter keeps 10 rows but it actually keeps 100,000, every decision built on that belief â join order, join strategy, whether to sort or index-walk â is wrong. Reading plans is mostly the art of finding those belief gaps.
EXPLAIN shows the plan without running it. EXPLAIN ANALYZE runs it and reports actual timings and row counts next to the estimates. You can also use EXPLAIN (ANALYZE, BUFFERS) to see how many pages were read from disk versus served from cache, which separates CPU-bound problems from I/O-bound ones.
EXPLAIN versus ANALYZE versus BUFFERS
Each mode answers a different question. Use the simplest one that answers yours.
| Command | Runs the query? | Shows | Use it when |
|---|---|---|---|
EXPLAIN | No | Estimated plan and costs | Comparing planner choices quickly; checking indexes without side effects |
EXPLAIN ANALYZE | Yes | Plan plus actual time, rows, loops | Confirming what really happens; finding estimate errors |
EXPLAIN (ANALYZE, BUFFERS) | Yes | Above plus shared hit/read blocks | Diagnosing I/O pressure and cache misses |
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) | Yes | Machine-readable plan | Feeding tools, dashboards, or plan-diff scripts |
Two cautions. First, EXPLAIN ANALYZE actually executes the statement, so running it on an UPDATE or DELETE will modify data (wrap it in a transaction and roll back if you only want the measurement). Second, planning time can matter too â very complex queries with dozens of joins may spend hundreds of milliseconds just choosing a plan, visible at the bottom of the output as Planning Time.
-- Measure a real query, then roll back so nothing changes
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.first_name, c.last_name, SUM(o.total) AS lifetime_value
FROM customers c
INNER JOIN orders o ON o.customer_id = c.id
WHERE o.order_date >= DATE '2024-01-01'
GROUP BY c.id, c.first_name, c.last_name
HAVING SUM(o.total) > 500
ORDER BY lifetime_value DESC
LIMIT 20;
ROLLBACK;
Anatomy of a Plan Tree
PostgreSQL prints the plan as an indented tree: children execute first and feed rows into their parent. Read from the innermost (most indented) nodes outward. A typical line looks like this:
Hash Join (cost=482.10..1204.55 rows=8420 width=48)
Hash Cond: (o.customer_id = c.id)
Buffers: shared hit=3120 read=884
-> Seq Scan on orders o (cost=0.00..612.00 rows=42100 width=24)
Filter: (order_date >= '2024-01-01'::date)
Rows Removed by Filter: 57900
Buffers: shared hit=2100 read=884
-> Hash (cost=312.00..312.00 rows=11200 width=20)
Buckets: 16384 Memory Usage: 512kB
Buffers: shared hit=1020
-> Seq Scan on customers c (cost=0.00..312.00 rows=11200 width=20)
Buffers: shared hit=1020
Three numbers on the parent line matter most: the estimated cost range, the estimated rows, and width (average row width in bytes). Under EXPLAIN ANALYZE each node gains an actual time window and an actual rows value that repeats per loop. If a node reports actual rows=1,000,000 but the estimate was rows=200, the planner dramatically underestimated the filter's selectivity â usually because statistics are stale or the expression is not something the planner models well (for example, a function applied to a column).
Join Strategies and When Each Wins
The planner picks among three join algorithms, and the choice often decides whether a query runs in 50 ms or 50 seconds.
| Strategy | How it works | Best when | Warning sign |
|---|---|---|---|
| Nested loop | For each outer row, probe the inner side | Inner side is a tiny index-backed lookup; outer row count is small | Inner side is a sequential scan that runs once per outer row (loops in the thousands) |
| Hash join | Build a hash table on the smaller input, stream the larger one | Neither input is pre-sorted; both are larger than cache-friendly | Hash table spills to disk â watch Hash Batches and Disk Usage |
| Merge join | Sort both inputs (or use pre-sorted index scans), then merge | Both inputs arrive sorted on the join key | Up-front sort cost dominates when inputs were already usable via index |
A nested loop with loops=400000 on the inner side is the classic disaster: the planner trusted a bad row estimate and picked a strategy that rescans too often. Fixing it usually means refreshing statistics, simplifying a filter so the planner can model it, or forcing better estimates with a join order the planner would choose once estimates improve.
Red Flags You Can Spot in Seconds
Some patterns are almost always a problem in production plans:
- Seq Scan on a large filtered table â a
Filteron an unindexed column means every row is read. Add a btree index on the filtered column, or reconsider the query if the filter is un-sargable (for example,WHERE LOWER(email) = ...cannot use a plain index onemail). - Rows Removed by Filter in the millions â the predicate is evaluated too late or cannot use an index. Check data types: comparing a
varcharcolumn to a date literal forces conversion per row. - Massive actual-versus-estimated gaps â run
ANALYZE table_name;to refresh statistics. For skewed data, extended statistics or a partial index may be needed. - Sort Node with huge
Memory UsageandDisk Usage: ...â the work_mem budget was too small for the sort; either raisework_memfor the session or add an index that delivers pre-sorted rows. - Repeated identical subplans â consider materializing with a CTE (in older PostgreSQL versions) or a temporary table.
A Repeatable Tuning Loop
Performance work rewards discipline. Follow the same loop every time so you can tell which change helped.
- Capture the baseline: run
EXPLAIN (ANALYZE, BUFFERS)inside a transaction and save the output. - Identify the single most expensive node â usually the one with the largest actual time or the biggest buffer count.
- Form one hypothesis: stale statistics, missing index, bad join order, spilled sort, oversized result.
- Change exactly one thing â
ANALYZE, oneCREATE INDEX, one rewritten predicate â never three at once. - Re-run and diff. If the plan improved but latency did not, the bottleneck is elsewhere (network, client rendering, connection pool).
-- Refresh statistics after a bulk load, then re-check the plan
ANALYZE orders;
ANALYZE customers;
-- Example of making a predicate sargable: index the column, filter on it directly
CREATE INDEX idx_orders_customer_date ON orders (customer_id, order_date);
-- Now the nested-loop probe can use an index scan instead of rescanning
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, SUM(total)
FROM orders
WHERE order_date BETWEEN DATE '2024-01-01' AND DATE '2024-12-31'
GROUP BY customer_id;
How Other Dialects Report Plans
The ideas transfer even when syntax does not.
| Engine | Command | Notes |
|---|---|---|
| PostgreSQL | EXPLAIN (ANALYZE, BUFFERS) | Tree output; JSON and XML formats available |
| MySQL 8.0.18+ | EXPLAIN ANALYZE | Tree output; earlier versions use tabular EXPLAIN |
| MySQL (classic) | EXPLAIN FORMAT=JSON | Richer cost and nested-loop detail than the table format |
| SQL Server | SET STATISTICS IO, TIME ON plus actual execution plan in SSMS | Look at estimated versus actual rows in the XML plan |
| Oracle | EXPLAIN PLAN FOR then read PLAN_TABLE; DBMS_XPLAN.DISPLAY_CURSOR for actuals | A-Rows column plays the role of actual rows |
Whichever engine you use, the diagnostic questions are identical: did the engine use the index you expected, are the row estimates close to reality, and did join and sort strategies match the data shapes you have?
Common Mistakes
Treating cost numbers as milliseconds and optimizing the wrong node
Fix: Compare costs only within one plan; use actual time from ANALYZE for real-world numbers
Running EXPLAIN ANALYZE on UPDATE or DELETE in production and committing the changes
Fix: Wrap it in BEGIN and ROLLBACK, or test on a read replica
Seeing a sequential scan and adding an index reflexively
Fix: Check the table size and selectivity first â a seq scan is often the fastest plan for large fractions of a table
Ignoring loops= on inner nodes
Fix: Multiply time by loops; a 0.02 ms inner node looping 500,000 times is your real cost
Adding indexes without removing them
Fix: Every index slows writes; drop redundant single-column indexes once a composite index covers the same prefixes
Best Practices
- Always capture a baseline plan before changing anything
- Use EXPLAIN (ANALYZE, BUFFERS) on production-shaped data, not tiny development tables
- Run ANALYZE after bulk loads so the planner works with fresh statistics
- Prefer sargable predicates so indexes stay usable
- Store golden plans as JSON in version control and diff them in CI for critical queries
Interview Questions
Q1: What is the difference between EXPLAIN and EXPLAIN ANALYZE?
EXPLAIN shows the planner's estimated plan without executing the statement. EXPLAIN ANALYZE executes it and adds actual time, actual rows, and loop counts beside each estimate, which reveals where estimates diverged from reality.
Q2: A plan shows a nested loop with loops=250000 on the inner node. What is wrong and how do you fix it?
The planner underestimated the outer row count and chose a nested loop whose inner side is re-executed per row. Refresh statistics, make the filter sargable, or rewrite the query so a hash join is chosen; verify with a new ANALYZE run.
Q3: When is a sequential scan the correct plan?
When the query needs a large fraction of the table â roughly more than a few percent â reading every page sequentially is cheaper than random index lookups, so the planner correctly picks a seq scan.
Key Takeaways
- EXPLAIN is free to run; EXPLAIN ANALYZE executes the query, so protect writes with a transaction
- Costs are relative planner units â actual time and rows are what you feel in production
- The gap between estimated and actual rows is the first thing to investigate in any bad plan
- Join strategy mismatches caused by stale statistics are a top cause of sudden slowdowns
- Tune with a loop: baseline, one hypothesis, one change, re-measure