Sub topic 7
Spotting misestimates in EXPLAIN ANALYZE
This chapter assumes you can run psql, read a simple EXPLAIN plan, and have the orders table from the earlier chapters. You should also know that ANALYZE fills pg_class and pg_stats. Here you learn to find where the planner's row estimates diverge from reality, and which divergences matter.
Two numbers on every line
EXPLAIN alone prints only the planner's guesses. EXPLAIN ANALYZE also runs the query and prints what happened. Each plan node then carries two row counts:
rows=inside the first parentheses is the estimate. It comes from statistics.rows=inside the second parentheses, next toactual time, is the actual count measured during execution.
EXPLAIN (ANALYZE)
SELECT * FROM orders WHERE status = 'pending';On the sample data, the output looks like this (your numbers and timings will differ):
Seq Scan on orders (cost=0.00..1887.00 rows=5012 width=28) (actual time=0.015..9.870 rows=4968 loops=1)
Filter: (status = 'pending'::text)
Rows Removed by Filter: 95032
Planning Time: 0.080 ms
Execution Time: 10.400 msThe estimate is 5012 and the actual count is 4968. That is a good estimate, because pending appears in the most-common-values list with a frequency near 0.05. Compare this with a query where the estimate is far off, which is what the rest of the chapter shows how to find.
Reading the numbers correctly
Three details cause most misreadings.
Per-loop counts
Both numbers are per execution of the node. A node on the inner side of a nested loop may run thousands of times. The actual rows figure is the average per loop, rounded. To get the total, multiply by loops.
Index Scan using orders_customer_idx on orders o
(cost=0.29..8.31 rows=1 width=28) (actual time=0.010..0.450 rows=100 loops=1000)Here the estimate is 1 row per loop, and each loop returns 100 on average. The planner expected 1,000 rows in total and the node returned 100,000. The error factor is 100, not 1.
Filtered rows
For a scan with a filter, actual rows counts rows that passed the filter. Rows Removed by Filter counts rows that were read and discarded. A large removed count with a small result suggests an index could help. It does not by itself indicate a bad estimate.
Nodes that stop early
Under a Limit, children may stop before producing all their rows, so their actual counts are smaller than their estimates. That is normal. A node marked (never executed) has no actual count at all. Do not treat either case as a misestimate.
How large an error matters
A small error rarely changes a plan. Look at the ratio between estimate and actual, and treat the ratio as the signal.
| Ratio (actual ÷ estimate) | Typical meaning |
|---|---|
| 0.5 to 2 | Normal. Ignore it. |
| 2 to 10 | Worth a glance. Matters only if the node feeds a join or sort. |
| More than 10 or less than 0.1 | A real misestimate. Investigate. |
| 1000 or more | Plan choice is probably wrong. Fix this first. |
The direction of the error changes the damage:
- Underestimates are usually worse. The planner picks a nested loop with an index lookup because it expects a few rows, then runs it for millions.
- Overestimates tend to give a hash join or sequential scan where an index would have been faster. This wastes memory and time, but rarely makes a query run for hours.
Where to look: the first big gap
Errors compound upward. If a scan is off by 100 times, the join above it inherits the error, and so does the join above that. The numbers at the top of the plan are often wrong only because of something below. Read from the leaves toward the root and find the lowest node whose estimate is badly wrong. That node, not the top one, tells you which statistic is at fault.
A worked misestimate: stale statistics
The simplest way to produce a bad estimate is to change the data after ANALYZE. This session adds a new status value and does not re-analyze.
INSERT INTO orders (customer_id, status)
SELECT (random() * 1000)::int, 'backorder'
FROM generate_series(1, 50000);
EXPLAIN (ANALYZE)
SELECT * FROM orders WHERE status = 'backorder';Typical output (illustrative):
Seq Scan on orders (cost=0.00..2137.00 rows=1 width=28) (actual time=0.020..12.300 rows=50000 loops=1)
Filter: (status = 'backorder'::text)
Rows Removed by Filter: 100000The estimate is 1 row and 50,000 came back. The statistics saw only shipped and pending. A value that is not in the most-common-values list gets a tiny share of the leftover fraction, which here is nearly zero. A one-row estimate is a warning sign in itself, because the planner rarely goes below 1 and often rounds up to it.
Now check whether statistics are stale, using the query from the earlier chapter:
SELECT relname, last_analyze, last_autoanalyze, n_mod_since_analyze
FROM pg_stat_user_tables
WHERE relname = 'orders';n_mod_since_analyze will be near 50,000, and both analyze timestamps will predate the insert. Fix it and compare:
ANALYZE orders;
EXPLAIN (ANALYZE)
SELECT * FROM orders WHERE status = 'backorder';The estimate should now be close to 50,000. This is the fast diagnostic: if running ANALYZE repairs the estimate, the cause was staleness. If the estimate stays wrong, the cause is something the statistics cannot express.
Common causes and what they look like
| Symptom in the plan | Likely cause | Next step |
|---|---|---|
| Estimate wrong right after a bulk load | Stale statistics | Run `ANALYZE`; check autoanalyze settings |
| Estimate wrong for a rare value in a large skewed column | Statistics target too low | Raise the target for that column |
| Estimate too low when two columns are filtered together | Correlated columns, independence assumed | Create extended statistics |
| Estimate wrong on a filter that wraps a column in a function | No statistics on the expression | Use an expression index or extended statistics on the expression |
| Estimate wrong for a join output | Bad estimate on a join key, or skew between the tables | Check `n_distinct` and MCVs on both keys |
| Estimate is a round default such as 1000 or 200 | Planner has no statistics at all | Analyze the table, or the table is a function result or CTE |
The independence assumption
When a query has WHERE city = 'Leeds' AND zip = 'LS1', the planner multiplies the two selectivities as if the columns were unrelated. If every LS1 row is in Leeds, the true selectivity is just that of zip, and the product is far too small. You see this as an underestimate on a scan with a multi-column Filter. Extended statistics, covered in a later chapter, address it.
Getting more detail from the plan
Add options when the plain output is not enough:
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT o.id
FROM orders o
WHERE o.status = 'pending'
AND o.customer_id < 50;BUFFERSshows how many pages each node touched, which confirms whether a wrong plan did excess work.VERBOSElists the output columns of each node and the schema-qualified names, which helps when a plan is long.
Two caveats apply when you read these runs. First, EXPLAIN ANALYZE executes the statement, so wrap an INSERT, UPDATE, or DELETE in a transaction you roll back:
BEGIN;
EXPLAIN (ANALYZE)
UPDATE orders SET status = 'cancelled' WHERE status = 'pending';
ROLLBACK;Second, timing instrumentation adds overhead per node, so tiny nodes executed millions of times look slower than they are. Row counts are not affected by that overhead, which is why they are the reliable part of the output.
Parallel and repeated nodes
In a parallel plan, a node under Gather reports row counts per worker process, averaged, with the number of workers shown by Workers Launched. Multiply by workers plus the leader to estimate the total, or read the Gather node above it, which reports the combined count. Nodes with loops=N for N greater than 1 follow the per-loop rule from earlier. In both cases, compare totals with totals. Comparing an estimate for one loop with an actual for a whole set of loops makes a correct plan look broken.
Summary of the habit
- Run
EXPLAIN (ANALYZE, BUFFERS)on the slow query, inside a rolled-back transaction if it writes. - Multiply actual rows by loops where needed.
- Find the lowest node with an error greater than about ten times.
- Check
last_autoanalyzeandn_mod_since_analyze. RunANALYZEand re-test. - If the error remains, classify it using the table above and apply the matching fix from the later chapters.
Exercise
A nested loop plan shows an inner node Index Scan ... (cost=0.29..8.31 rows=2 width=28) (actual time=0.008..0.030 rows=40 loops=5000). By what factor did the planner underestimate the rows this node returned in total, and why should you not just say "20 times"?
Show answer
The estimate was 2 rows per loop, or 10,000 rows in total across 5,000 loops. The actual was 40 rows per loop, or 200,000 rows in total. The factor is 20 for the total as well as per loop, but the total shows the real cost: 200,000 rows were fetched instead of 10,000. Reading only the per-loop figures hides how much work the node did, so multiply by loops before judging severity. You should also check whether the 5,000 loops were themselves expected by the node above, since the outer side may be misestimated too.
Exercise
After a nightly bulk load, a query's scan node estimates 3 rows but returns 80,000. You run ANALYZE on the table and the estimate becomes 79,500. What was the cause, and which two columns of pg_stat_user_tables would have pointed to it before you ran ANALYZE?
Show answer
The cause was stale statistics: the bulk load changed the data after the last analyze, so the stored most-common values and row counts no longer matched. last_autoanalyze (and last_analyze) would show a timestamp from before the load, and n_mod_since_analyze would show a large count of rows changed since then.