Sub topic 10
Comparing estimated and actual rows
This chapter assumes you can read a plan tree and know the cost, rows and width fields from earlier chapters. It also assumes you can run EXPLAIN (ANALYZE) and read its actual time output. The examples use PostgreSQL.
Why this comparison matters
The planner picks a plan from its estimates. If an estimate is wrong, the planner may choose a plan that is far from the best one. A nested loop that was chosen for 10 rows runs badly when 1,000,000 rows arrive. A sequential scan that was chosen for most of a table is wasteful when the filter keeps only 20 rows.
EXPLAIN alone shows only the estimates. EXPLAIN ANALYZE puts the estimate and the actual count on the same node, so you can compare them.
Seq Scan on addresses (cost=0.00..2300.00 rows=100 width=23)
(actual time=0.031..14.502 rows=1000 loops=1)
Filter: ((city = 'city_3') AND (zip_code = 35))
Rows Removed by Filter: 99000The first parenthesis holds the estimate: rows=100. The second holds the measurement: rows=1000. The planner expected 100 rows and got 1,000, so it underestimated by a factor of 10.
Reading the two numbers correctly
Three details cause most misreadings.
actual rowsis a per-loop average. A node that runs more than once reports the average rows per execution and the number of executions asloops. The total isrows × loops.- The estimate is also per execution. The estimated
rowson a node is the rows expected per loop, so compare it with the per-loopactual rows. Rows Removed by Filteris a separate count. It reports rows that were read and then discarded. It does not appear inrows. A large value means the node did a lot of work to return a few rows.
Here is an inner node of a nested loop:
-> Index Scan using orders_customer_id_idx on orders o
(cost=0.43..8.45 rows=3 width=40)
(actual time=0.012..0.020 rows=12 loops=5000)The planner expected 3 rows per execution. Each execution returned 12 on average, and the node ran 5,000 times. The node produced 60,000 rows in total, not 3 × 5,000 = 15,000 as estimated. The error is 4× per loop and also 4× in total. The loops count affects the total work, but the ratio you judge is rows against actual rows.
How big an error is a problem
A rule of thumb for judging the ratio between actual and estimated rows:
| Ratio (larger ÷ smaller) | Usual meaning |
|---|---|
| Under 2× | Normal. Ignore it. |
| 2× to 10× | Often harmless. Check only if the node is expensive. |
| 10× to 100× | Likely to affect the choice of join or scan. Investigate. |
| Over 100× | Probably the cause of a bad plan. Fix it first. |
The ratio matters most where a decision depends on it. A 50× error on a node that feeds a join is serious. The same error on a node that returns 3 rows instead of 150 usually costs nothing.
Errors propagate upward
An estimate on a child node feeds the estimates of its parent. A wrong row count at the bottom of the tree is carried upward and often grows. When you compare numbers, start at the deepest node where the estimate and actual first diverge by a large factor. That node is usually the source. The mismatches above it are often just consequences.
A harmless gap: LIMIT and early termination
Some gaps are not misestimates. A Limit node stops asking its child for rows once it has enough. The child then reports fewer actual rows than it estimated.
EXPLAIN (ANALYZE)
SELECT *
FROM orders
ORDER BY created_at
LIMIT 10;If created_at has an index, the plan is a Limit over an Index Scan. The scan node shows an estimate of the whole table but an actual count of 10, because it was stopped. A merge join can behave the same way when one input is exhausted before the other. Before you treat a gap as a problem, check whether a Limit or a merge join sits above the node.
Common causes of misestimates
- Stale statistics. A table changed a lot since the last
ANALYZE. A bulk load into a new table is the usual case, because autovacuum may not have run yet. - Correlated columns. The planner multiplies the selectivities of separate conditions as if the columns were independent. When one column determines another, such as
cityandzip_code, the result is far too small. - Skewed values. A few values are very common, but the statistics describe the average case. The
most common valueslist covers only a limited number of entries. - Expressions and functions. A condition like
lower(email) = '[email protected]'ordate_trunc('day', created_at) = ...has no column statistics. The planner falls back to a default guess unless an expression index or extended statistics exist. - Join conditions. Estimates for joins on multiple keys, or after filtering, are less reliable than single-table estimates.
Worked example: correlated columns
Build a table where each ZIP code belongs to exactly one city:
CREATE TABLE addresses AS
SELECT g AS id,
g % 100 AS zip_code,
'city_' || ((g % 100) / 10) AS city
FROM generate_series(1, 100000) AS g;
ANALYZE addresses;
EXPLAIN (ANALYZE)
SELECT *
FROM addresses
WHERE city = 'city_3'
AND zip_code = 35;There are 10 cities and 100 ZIP codes. ZIP code 35 belongs to city_3, so the second condition adds no new restriction. The true result is 1,000 rows. The planner estimates the selectivity of city as about 0.1 and of zip_code as about 0.01, then multiplies them: 100,000 × 0.1 × 0.01 = 100 rows. That is the 10× underestimate shown earlier.
Tell the planner that the columns depend on each other, then refresh the statistics:
CREATE STATISTICS addresses_city_zip_stats (dependencies)
ON city, zip_code FROM addresses;
ANALYZE addresses;
EXPLAIN (ANALYZE)
SELECT *
FROM addresses
WHERE city = 'city_3'
AND zip_code = 35;The estimate now comes out close to 1,000 rows. The dependencies kind records that zip_code determines city, so the planner no longer multiplies the two selectivities. The extended statistics apply only when the query uses equality conditions on the covered columns. Use ndistinct when the error appears in GROUP BY estimates, and mcv when specific value combinations are skewed.
Other fixes, in order of cost
- Run
ANALYZEon the table. It is cheap and fixes staleness. Checklast_analyzeandlast_autoanalyzeinpg_stat_user_tablesto see how old the statistics are. - Raise the statistics target for a column with skewed or high-cardinality data. This keeps more detail in
pg_stats.
``sql ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 1000; ANALYZE orders; ``
The default target is 100. A larger value makes ANALYZE slower and the statistics larger.
- Add extended statistics for correlated columns, as above.
- Create an expression index for a condition on an expression.
ANALYZEthen collects statistics on the expression too. - Rewrite the query so the planner can see the condition. Replace a function applied to a column with a range test on the bare column.
Checking your fix
After each change, run EXPLAIN (ANALYZE) again and compare three things: the estimated and actual rows on the node you changed, the join or scan type chosen above it, and the total execution time. A fix is working when the estimate moves close to the actual count. A faster query with an estimate that is still wrong may have been helped by chance, and the problem can return when the data changes.
Exercise
An inner node of a nested loop shows (cost=0.29..8.31 rows=2 width=16) (actual time=0.010..0.015 rows=9 loops=2000). How many rows did the node return in total, and by what factor did the planner underestimate per loop?
Show answer
The node returned 9 × 2000 = 18,000 rows in total. The planner estimated 2 rows per loop and the average actual was 9, so it underestimated by 4.5×. The planner expected about 4,000 rows in total.
Exercise
A Seq Scan under a Limit 10 node shows rows=500000 estimated and actual rows=10. Is this a misestimate you should fix? Why?
Show answer
No. The Limit node stopped requesting rows after 10, so the scan ended early. The estimate describes a full scan, and the actual count reflects the early stop. Compare the estimate and actual only on nodes that ran to completion.
Exercise
Two columns, country and currency, are strongly linked, and a query filtering on both has a 30× underestimate. Which statement fixes it, and what must you run afterward?
Show answer
CREATE STATISTICS name (dependencies) ON country, currency FROM tablename; then run ANALYZE tablename so the planner collects the new statistics. Re-run EXPLAIN (ANALYZE) to confirm the estimate is close to the actual count.