estimating rows
how a WHERE becomes a row count: MCVs, histogram buckets, and the default guesses when there's nothing to go on.
- address
- everything.optimizer.estimating_rows
- part
- part 10, the optimizer
- chapter
- chapter 3 of 10
- reading time
- 9 min
before it can price a plan, the planner needs a row count for every WHERE. it turns each condition into a selectivity (the fraction of rows that pass) using what ANALYZE wrote down: the most common values with their exact frequencies, a histogram of everything else, and the number of distinct values.
when there's nothing to go on, a function or an expression, it falls back to a fixed default guess: 0.005 for =, 1/3 for <.
the picture
you know how EXPLAIN says rows=34 for a user who has 19 events, and rows=34 again for one with 53? it isn't counting anything. it's reading a summary of the column and doing arithmetic on it.
think of a census office that keeps two things about a town: a list of the 100 biggest families with their exact headcounts, and, for everyone else, a line of 100 people sorted by surname with a marker every 1%. ask "how many Garcias?" and if Garcia is on the big-family list, you get the exact number. if not, you get "an average-sized family". ask "how many surnames before M?" and they count the big families before M, then see how many 1% markers come before M, and guess the bit between two markers.
that's pg_stats for events.user_id. pick a predicate and slide the value:
a most common value: the planner knows its exact share. on a table ANALYZE read in full, this is exact.
every estimate in that figure is the planner's own, captured from EXPLAIN, and the arithmetic under it is redone for each one. if it didn't land on the planner's number, this page wouldn't build.
equality: the MCV list, or an even share
ANALYZE keeps up to default_statistics_target (100) most common values per column, with the fraction of rows each one has:
SELECT (most_common_vals::text::int[])[1:5] AS top_5,
most_common_freqs[1:5] AS freqs,
array_length(most_common_freqs, 1) AS kept
FROM pg_stats
WHERE tablename = 'events' AND attname = 'user_id';| top_5int4[] | freqsfloat4[] | keptint4 |
|---|---|---|
| {1,2,3,4,18} | {0.04536,0.0184,0.0154,0.01244,0.0118} | 100 |
user 1 has 4.536% of the rows. for user_id = 1 the estimate is that, times the row count:
EXPLAIN SELECT * FROM events WHERE user_id = 1;
SELECT count(*) FROM events WHERE user_id = 1;| countint8 |
|---|
| 1134 |
0.04536 × 25,000 = 1,134, and so is the count. on these datasets the statistics are exact (every table is under 30,000 rows, so ANALYZE reads all of it: pg_stats and ANALYZE says why that's unusual), so an MCV hit is exact too.
a value that isn't in the list gets an even share of what the list leaves over. the 100 MCVs cover 45.844% of the rows; the other 54.156% is spread over the other 400 distinct values:
(1 − 0.45844 − 0) / (500 − 100) = 0.00135 → × 25,000 = 34 rows
for user 250 (35 rows), user 333 (32) and user 150 (53) alike. and for user 501, who doesn't exist: equality never looks at the histogram, so the planner has no idea 501 is past the end.
EXPLAIN SELECT * FROM events WHERE user_id = 250;
EXPLAIN SELECT * FROM events WHERE user_id = 333;ranges: count the spikes, then the buckets
for user_id < v, two parts add up:
- the MCVs below v, exactly: sum their frequencies.
- the histogram, for the other 54.156%. its 101 bounds cut those rows into 100 buckets of equal size, so each full bucket below v is 1% of them. for the bucket v lands in, the planner assumes the values inside are spread evenly and takes the fraction of the way across: v = 250 sits in the bucket [246, 250), 100% across.
SELECT (histogram_bounds::text::int[])[46:49] AS around_250
FROM pg_stats
WHERE tablename = 'events' AND attname = 'user_id';
EXPLAIN SELECT * FROM events WHERE user_id < 250;
SELECT count(*) FROM events WHERE user_id < 250;| around_250int4[] |
|---|
| {246,250,254,257} |
| countint8 |
|---|
| 17665 |
17,655 estimated, 17,665 real. step through the < values in the figure and the working shows each piece, including two small corrections postgres makes: < takes off one value's share (the histogram really answers <=), and an estimate outside the histogram is clamped to a sliver instead of 0 or 1, because the bounds may be out of date.
one level deeperwhy a histogram of the rest, and not of everything
the MCVs are taken out first, so the histogram only covers values that aren't common. otherwise user 1's 1,134 rows would eat four or five buckets on their own, and every bucket around them would be useless. postgres calls these equal-height (or equal-frequency) histograms: every bucket holds the same number of rows and the bounds move. the alternative, equal-width buckets, spends most of its buckets on empty ranges for skewed data like this.
combining conditions
a WHERE with several conditions gets one selectivity per condition, then:
a AND b: s(a) × s(b)a OR b: s(a) + s(b) − s(a) × s(b)NOT a: 1 − s(a)
the multiplication assumes the conditions are independent: knowing the kind tells you nothing about the user. when that's false the estimate can be off by orders of magnitude, which is the whole of when estimates go wrong, and the fix is extended statistics.
when there's nothing to go on
statistics are per column. wrap the column in a function or an expression and the planner can't see through it, so it uses a constant from selfuncs.h:
| predicatetext | estint8 | actualint8 |
|---|---|---|
| lower(kind) = 'view' | 125 | 15112 |
| props->>'device' = 'ios' | 125 | 8007 |
| user_id + 0 < 42 | 8333 | 7195 |
| user_id + 0 BETWEEN 100 AND 110 | 125 | 622 |
| user_id BETWEEN 100 AND 110 | 615 | 622 |
| amount IS NULL | 23235 | 23235 |
the defaults, as postgres 18 defines them: DEFAULT_EQ_SEL 0.005, DEFAULT_INEQ_SEL 1/3, DEFAULT_RANGE_INEQ_SEL 0.005, DEFAULT_MATCH_SEL 0.005 for pattern matches, and DEFAULT_NUM_DISTINCT 200 when even the distinct count is unknown. lower(kind) = 'view' is a 121x miss: 125 guessed, 15,112 real. try it:
EXPLAIN SELECT * FROM events WHERE lower(kind) = 'view';
EXPLAIN SELECT * FROM events WHERE kind = 'view';two ways out. write the condition so it uses the bare column (kind = 'view'), or give the planner statistics on the expression. an expression index gets its own statistics at the next ANALYZE, and so does CREATE STATISTICS on an expression, without the index (extended statistics).
WHERE props->>'device' = 'ios' is estimated at 125. where does 125 come from?keylines
- every condition becomes a selectivity, times the table's row count.
- equality: an MCV's exact frequency, or an even share of what the MCVs leave over.
- ranges: the MCVs that pass, plus histogram buckets, interpolated inside the last one.
- AND multiplies, OR adds and subtracts the overlap. both assume independence.
- no statistics (functions, expressions): 0.005 for =, 1/3 for
<. a round estimate is a guess.