skip to content

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:

WHERE
value =
42
user_id = 420100200300400500√
most common values (spikes) and histogram buckets: what ANALYZE wrote downthe part this estimate reads
42 is most common value #48, with frequency 0.00336
0.00336 × 25,000 rows = 84 → 84
estimate 84actual 84closeselectivity 0.336%

a most common value: the planner knows its exact share. on a table ANALYZE read in full, this is exact.

real output, postgres 18.6 (PGlite 0.5.12) · selectivity
the spikes are user_id's 100 most common values, the blocks the histogram of the other 400: 100 buckets holding the same number of rows each, so a narrow block means dense values. slide the value and the part of the statistics the estimate reads goes hot. try = 1 (a spike), = 250 (no spike), = 501 (past the end), then the same values with <, then the + 0 versions.

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:

sqldb=events
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';
output, from postgres 18.6
SELECT 1
top_5int4[]freqsfloat4[]keptint4
{1,2,3,4,18}{0.04536,0.0184,0.0154,0.01244,0.0118}100
(1 row)

user 1 has 4.536% of the rows. for user_id = 1 the estimate is that, times the row count:

sqldb=events
EXPLAIN SELECT * FROM events WHERE user_id = 1;
SELECT count(*) FROM events WHERE user_id = 1;
output, from postgres 18.6
#1 · EXPLAIN
Seq Scan on events (cost=0.00..647.50 rows=1134 width=78) Filter: (user_id = 1)
#2 · SELECT 1
countint8
1134
(1 row)

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.

predict the output
user_id = 250 and user_id = 333 both aren't MCVs. which gets the bigger estimate?
sql
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.
sqldb=events
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;
output, from postgres 18.6
#1 · SELECT 1
around_250int4[]
{246,250,254,257}
(1 row)
#2 · EXPLAIN
Seq Scan on events (cost=0.00..647.50 rows=17655 width=78) Filter: (user_id < 250)
#3 · SELECT 1
countint8
17665
(1 row)

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)
purchase: est1,765
purchase: real1,765
user_id < 42: est7,204
user_id < 42: real7,195
purchase AND < 42: est509
purchase AND < 42: real545
purchase OR < 42: est8,461
purchase OR < 42: real8,415
NOT purchase: est23,235
NOT purchase: real23,235
signup AND user 1: est23
signup AND user 1: real1
log scale
real output, postgres 18.6 (PGlite 0.5.12) · selectivity
estimated and real rows for combinations of two predicates on events, on a log scale. AND and OR come out close here because kind and user_id are nearly independent. the last one isn't: every user's first event is their signup, so user 1 has exactly one, and the planner multiplies its way to 23.

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:

predicatetextestint8actualint8
lower(kind) = 'view'12515112
props->>'device' = 'ios'1258007
user_id + 0 < 4283337195
user_id + 0 BETWEEN 100 AND 110125622
user_id BETWEEN 100 AND 110615622
amount IS NULL2323523235
(6 rows)
real output, postgres 18.6 (PGlite 0.5.12) · selectivity
conditions the column statistics don't cover. the guesses never look at the value: = gets 0.005 of the table, < gets a third, a two-sided range 0.005. the BETWEEN on the bare column is there for contrast, and IS NULL reads null_frac.

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:

sqldb=events
EXPLAIN SELECT * FROM events WHERE lower(kind) = 'view';
EXPLAIN SELECT * FROM events WHERE kind = 'view';
output, from postgres 18.6
#1 · EXPLAIN
Seq Scan on events (cost=0.00..710.00 rows=125 width=78) Filter: (lower(kind) = 'view'::text)
#2 · EXPLAIN
Seq Scan on events (cost=0.00..647.50 rows=15112 width=78) Filter: (kind = 'view'::text)

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).

quick check
events has 25,000 rows. 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.