skip to content

when estimates go wrong

the independence assumption, functions in WHERE, and the 1,000x miss that picks a nested loop.

address
everything.optimizer.misestimates
part
part 10, the optimizer
chapter
chapter 4 of 10
reading time
8 min

the planner's row estimates rest on assumptions, and the big one is independence: two conditions on different columns are treated as unrelated, so their selectivities multiply. on columns that move together that's wrong by the whole selectivity of the extra condition, every time you add one.

a bad estimate low in a plan compounds on the way up, and a plan built for 1 row runs on 1,000. here's one that picks a nested loop because of it.

the picture

you know how a query is fast for months and then one day it isn't, and nothing changed? usually something did: the data. and the planner's picture of it didn't.

think of a party planner who knows 1 in 30 guests is from the marketing team, and 1 in 30 sits at table 7, and 1 in 30 ordered the vegetarian meal. asked "how many marketing people at table 7 ordered vegetarian?", they multiply: 1 in 27,000. but marketing all sit at table 7, and the whole team is vegetarian. the real answer is 1 in 30.

that's a table of support tickets where each team works one queue in one region. team = 7 already means queue = 7 and region = 7, and postgres has no way to know:

sqldb=shop · session tix
CREATE TABLE tickets (id int PRIMARY KEY, team int NOT NULL, queue int NOT NULL, region int NOT NULL,
                      customer_id int NOT NULL REFERENCES customers);
INSERT INTO tickets
SELECT i, i % 30, i % 30, i % 30, 1 + (i * 37) % 2000
FROM generate_series(1, 30000) AS i
ORDER BY i;
CREATE INDEX orders_customer_id ON orders (customer_id);
ANALYZE tickets;
ANALYZE orders;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT * FROM tickets WHERE team = 7 AND queue = 7 AND region = 7;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 30000
#3 · CREATE INDEX
#4 · ANALYZE
#5 · ANALYZE
#6 · EXPLAIN
Seq Scan on tickets (cost=0.00..717.00 rows=1 width=20) (actual rows=1000.00 loops=1) Filter: ((team = 7) AND (queue = 7) AND (region = 7)) Rows Removed by Filter: 29000 Buffers: shared hit=192 Planning: Buffers: shared hit=26

rows=1 estimated, rows=1000.00 actual. each condition alone is 1/30 of the table, and the estimate multiplies all three:

1 condition: est1,000
1 condition: real1,000
2 conditions: est33
2 conditions: real1,000
3 conditions: est1
3 conditions: real1,000
log scale
real output, postgres 18.6 (PGlite 0.5.12) · misestimate
the same 1,000 tickets, described with one, two and three conditions. each extra condition divides the estimate by 30 and changes nothing about the result. the third is a 1,000x miss.

30,000 × 1/30 × 1/30 × 1/30 = 1.1, rounded to 1. (estimating rows has the AND rule.) the independence assumption isn't laziness: per-column statistics can't say anything about pairs, and storing every pair is too much. the fix is to tell postgres which pairs matter, which is extended statistics.

the plan that follows

a misestimate on its own is harmless. it hurts when it changes the plan. join those tickets to their customers' orders:

sqldb=shop · session tix
continues session tix (1 earlier block run first)
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS)
SELECT count(*)
FROM tickets AS t
JOIN orders AS o ON o.customer_id = t.customer_id
WHERE t.team = 7 AND t.queue = 7 AND t.region = 7;
output, from postgres 18.6
EXPLAIN
Aggregate (cost=721.43..721.44 rows=1 width=8) (actual rows=1.00 loops=1) Buffers: shared hit=2180 read=13 -> Nested Loop (cost=0.29..721.42 rows=5 width=0) (actual rows=4705.00 loops=1) Buffers: shared hit=2180 read=13 -> Seq Scan on tickets t (cost=0.00..717.00 rows=1 width=4) (actual rows=1000.00 loops=1) Filter: ((team = 7) AND (queue = 7) AND (region = 7)) Rows Removed by Filter: 29000 Buffers: shared hit=192 -> Index Only Scan using orders_customer_id on orders o (cost=0.29..4.37 rows=5 width=4) (actual rows=4.71 loops=1000) Index Cond: (customer_id = t.customer_id) Heap Fetches: 0 Index Searches: 1000 Buffers: shared hit=1988 read=13 Planning: Buffers: shared hit=33 read=6

for one ticket, a nested loop is the obvious plan: find the ticket, probe the index on orders.customer_id once. it ran 1,000 probes:

show =
actual rowsestimated rowsestimate off by 10× or morebuffer hits
real output, postgres 18.6 (PGlite 0.5.12) · misestimate
the plan postgres picked, with estimated and actual rows on every node. the seq scan's 1 against 1,000 is where it goes wrong; the join's 5 against 4,705 is the same mistake, carried up. loops=1000 on the index-only scan is the price: one descent per ticket the planner didn't expect.

with the right estimate (the next block tells postgres the columns are related, a preview of the next chapter), it reads the 1,000 tickets, sorts them by customer, and walks the index on orders once, in order:

sqldb=shop · session tix
continues session tix (2 earlier blocks run first)
CREATE STATISTICS tickets_team (dependencies) ON team, queue, region FROM tickets;
ANALYZE tickets;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS)
SELECT count(*)
FROM tickets AS t
JOIN orders AS o ON o.customer_id = t.customer_id
WHERE t.team = 7 AND t.queue = 7 AND t.region = 7;
output, from postgres 18.6
#1 · CREATE STATISTICS
#2 · ANALYZE
#3 · EXPLAIN
Aggregate (cost=1097.61..1097.62 rows=1 width=8) (actual rows=1.00 loops=1) Buffers: shared hit=209 -> Merge Join (cost=767.11..1085.11 rows=5000 width=0) (actual rows=4705.00 loops=1) Merge Cond: (o.customer_id = t.customer_id) Buffers: shared hit=209 -> Index Only Scan using orders_customer_id on orders o (cost=0.29..218.28 rows=10000 width=4) (actual rows=10000.00 loops=1) Heap Fetches: 0 Index Searches: 1 Buffers: shared hit=17 -> Sort (cost=766.83..769.33 rows=1000 width=4) (actual rows=4740.00 loops=1) Sort Key: t.customer_id Sort Method: quicksort Memory: 17kB Buffers: shared hit=192 -> Seq Scan on tickets t (cost=0.00..717.00 rows=1000 width=4) (actual rows=1000.00 loops=1) Filter: ((team = 7) AND (queue = 7) AND (region = 7)) Rows Removed by Filter: 29000 Buffers: shared hit=192 Planning: Buffers: shared hit=36
nested loop (est. 1 ticket)2,193 pages
merge join (est. 1,000)209 pages
real output, postgres 18.6 (PGlite 0.5.12) · misestimate
pages the two plans asked the buffer pool for (Buffers: shared hit + read at the top node). same 4,705 rows out. the nested loop's extra pages are the 1,000 index descents.

2,193 pages against 209. in the browser every one of them is a cached hit, so the difference is small in time. on a server with a cold cache, every index descent is random reads, and the nested loop is the plan that takes minutes. the bigger the outer side really is, the worse it gets: the nested loop's cost grows with outer rows × inner probe, and the planner was sure the outer side was 1.

predict the output
the seq scan on tickets is 1,000x off. how far off is the Nested Loop above it?
text
Nested Loop  (rows=5) (actual rows=4705.00)
  ->  Seq Scan on tickets t  (rows=1) (actual rows=1000.00)
  ->  Index Only Scan using orders_customer_id on orders o  (rows=5) (actual rows=4.71 loops=1000)

where misestimates come from

correlated columns. the case above: city and country, model and make, team and queue. the estimate is too low by roughly the selectivity of every redundant condition.

a function or expression on the column. WHERE lower(kind) = 'view' has no statistics, so the planner uses its default of 0.005:

sqldb=events
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT * FROM events WHERE lower(kind) = 'view';
output, from postgres 18.6
EXPLAIN
Seq Scan on events (cost=0.00..710.00 rows=125 width=78) (actual rows=15112.00 loops=1) Filter: (lower(kind) = 'view'::text) Rows Removed by Filter: 9888 Buffers: shared read=335 Planning: Buffers: shared hit=45 read=2

125 against 15,112, 121x low. date_trunc('day', ts) = …, coalesce(x, 0) > 5, col + 0, a cast on the column side: same story. write the condition on the bare column, or give the expression statistics (an expression index, or CREATE STATISTICS on the expression, see extended statistics).

stale statistics. a table that changed since its last ANALYZE (pg_stats and ANALYZE): new values missing from the MCV list, a histogram that ends before today's rows.

skew the summary can't hold. a value outside the MCV list gets an average share. if the column has thousands of values and a few dozen of them are huge, a bigger statistics target is the fix.

a value the planner doesn't know yet. a prepared statement's generic plan is planned for $1, any value, so it gets an average estimate even when the value you pass is rare.

joins. a join's estimate is built from the n_distinct of both join columns and every estimate below it. it's usually the least accurate number in a plan, and the one that decides the next join's algorithm.

finding the one that matters

run EXPLAIN ANALYZE and read it bottom-up for the lowest node where estimated and actual rows differ by 10x or more (EXPLAIN ANALYZE explains loops: compare per-loop numbers). everything above it is planned on bad information, so fixing anything above it is fixing the symptom. this book's plan figures mark those nodes in dead.

keylines

  • independence: selectivities of different columns multiply. correlated columns break it.
  • functions and expressions on a column have no statistics: the planner guesses 0.005.
  • errors compound up the plan: a join inherits the error of what's below it.
  • the plan that hurts most from underestimates is a nested loop with a big outer side.
  • read EXPLAIN ANALYZE bottom-up for the lowest 10x gap, and fix that estimate.