Sub topic 6
How statistics become row estimates
This chapter assumes you can read EXPLAIN output and have seen pg_stats (covered in earlier chapters). It shows the arithmetic the planner does with those statistics to predict how many rows a plan node returns. Once you know the arithmetic, a bad estimate becomes something you can trace to a cause.
The basic formula
For a scan with a WHERE clause, the planner computes:
estimated rows = table row count × selectivitySelectivity is the fraction of rows the condition keeps, between 0 and 1. It comes from pg_stats.
The table row count is not simply pg_class.reltuples. The planner reads the table's current size in pages from the filesystem. It then scales the density reltuples / relpages by that current page count. A table that has grown since the last ANALYZE therefore still gets a reasonably scaled row count. That is why reltuples can look stale while the estimate stays close.
Each operator uses a different rule to get its selectivity:
| Condition | Statistic used |
|---|---|
| `col = constant` and the constant is a most common value (MCV) | The MCV's stored frequency |
| `col = constant` and the constant is not an MCV | The leftover fraction divided among the remaining distinct values |
| `col < constant` or `BETWEEN` | The histogram, plus the MCV list |
| `col IS NULL` | `null_frac` |
| Several conditions joined by `AND` | Selectivities multiplied together |
Sample data
This chapter uses the orders table from earlier chapters, in which about 95% of rows are shipped and 5% are pending. Run ANALYZE orders; first if you have not. Sampling makes the exact frequencies vary slightly between runs.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id int NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO orders (customer_id, status)
SELECT (random() * 1000)::int,
CASE WHEN random() < 0.95 THEN 'shipped' ELSE 'pending' END
FROM generate_series(1, 100000);
ANALYZE orders;Equality on a most common value
ANALYZE stores the frequent values of a column in most_common_vals, with their fractions in most_common_freqs. For status = 'pending' the planner finds pending in the list and uses its frequency directly.
You can reproduce the estimate yourself. This query multiplies each stored frequency by the table's row count:
SELECT u.val AS status,
u.freq,
round(u.freq::float8 * c.reltuples::float8) AS estimated_rows
FROM pg_stats s
CROSS JOIN pg_class c
CROSS JOIN LATERAL unnest(s.most_common_vals::text::text[],
s.most_common_freqs) AS u(val, freq)
WHERE s.schemaname = 'public'
AND s.tablename = 'orders'
AND s.attname = 'status'
AND c.relname = 'orders';Now compare with the planner's own number:
EXPLAIN SELECT * FROM orders WHERE status = 'pending';Seq Scan on orders (cost=0.00..1887.00 rows=4960 width=...)
Filter: (status = 'pending'::text)The rows= value should be close to the estimated_rows your query printed for pending. It is not exactly 5000 because the statistics come from a random sample.
Equality on a value that is not an MCV
When the constant is not in the MCV list, the planner cannot look up a frequency. It assumes the rows not covered by the MCVs and NULLs are spread evenly across the remaining distinct values:
selectivity = (1 - sum(mcv_freqs) - null_frac) / (n_distinct - number_of_mcvs)Two details matter here:
- If
n_distinctis negative, it means a fraction of the row count. A value of-1means every row is distinct. The planner multiplies by the row count to get the real number. - The planner never estimates fewer than one row for a node, however small the formula's result.
You can see the second effect by asking for a status that does not exist:
EXPLAIN SELECT * FROM orders WHERE status = 'returned';Seq Scan on orders (cost=0.00..1887.00 rows=1 width=...)
Filter: (status = 'returned'::text)The two MCVs cover essentially 100% of the rows. The leftover fraction is near zero, so the estimate is clamped to one row.
A column such as customer_id has roughly 1,000 distinct values with similar frequencies, so few or none of them qualify as MCVs. For customer_id = 42, the estimate is close to the average: about 100000 / 1001, or 100 rows. The planner treats every value as equally common.
Ranges and the histogram
For <, > and BETWEEN, the planner uses histogram_bounds. The histogram divides the non-MCV values into buckets that each hold about the same number of rows. With the default default_statistics_target of 100, there are up to 100 buckets.
To estimate customer_id < 250, the planner does three things:
- It counts the whole buckets whose upper bound is below 250.
- It interpolates linearly inside the bucket that contains 250, assuming values are spread evenly within it.
- It divides that count of buckets by the total number of buckets.
If the MCV list is non-empty, the planner adds the frequencies of the MCVs that satisfy the condition. The histogram result is scaled to the fraction of rows not covered by MCVs and NULLs.
EXPLAIN SELECT * FROM orders WHERE customer_id < 250;Seq Scan on orders (cost=0.00..1887.00 rows=24900 width=...)
Filter: (customer_id < 250)The estimate is about a quarter of the table because 250 is about a quarter of the way through the value range. The interpolation inside one bucket is the main source of error. If the values within a bucket are heavily skewed, the straight-line assumption is wrong. A finer histogram, which a higher statistics target gives you, reduces that error.
Combining conditions
For WHERE a AND b, the planner multiplies the two selectivities. That is correct only if the columns are statistically independent.
EXPLAIN SELECT * FROM orders
WHERE status = 'pending' AND customer_id = 42;Here the arithmetic is 0.05 × (1/1001) × 100000, which is about 5 rows. In this table status and customer_id were generated independently, so the estimate is good.
Now take two columns that are not independent. In a table of addresses, city = 'Paris' and zip = '75001' select almost the same rows. If each condition keeps 1%, the planner multiplies them to 0.01% and predicts 100 times fewer rows than exist. The plan nodes above this scan inherit that error. Extended statistics, covered in a later chapter, exist to fix this.
For OR, the planner combines selectivities as s1 + s2 - s1 × s2. It uses the same independence assumption.
The whole estimation path
Cases where the planner falls back to defaults
If the planner has no statistics, or cannot use them, it uses hard-coded default selectivities. Common situations are:
- A table that has never been analyzed. Equality gets a default of about 0.5% of rows (
1/200), and ranges get about 33%. - An expression with no statistics.
WHERE lower(status) = 'pending'has no stats onlower(status), unless an expression index or extended statistic exists. The planner falls back to the default. - A comparison with another column.
WHERE created_at > updated_athas no constant to look up, so the planner uses a flat default. - A parameter the planner cannot see. A generic plan for a prepared statement does not know the parameter value. It estimates with the average frequency, not the frequency of the actual value.
Where estimates go wrong
The planner is accurate when each of its assumptions holds. These are the usual places for them to break:
- Stale statistics. The data changed after the last analyze, so MCV frequencies and histogram bounds describe old data.
- A distribution too fine for the target. More distinct heavy values exist than the MCV list can hold, or the histogram is too coarse.
- Correlated columns. Selectivities are multiplied when they should not be.
- Expressions and function calls. The planner has no statistics for the result and uses defaults.
- Joins. The planner estimates join selectivity from the
n_distinctand MCV lists of both join columns. Errors in either side multiply through the join.
An estimate off by a factor of two rarely changes a plan. The damaging errors are off by 10× or more, especially when they make the planner choose a nested loop over a hash join, or a sequential scan over an index scan, for the wrong reasons.
Exercise
A table events has 2,000,000 rows. For its kind column, pg_stats shows most_common_vals = {click,view}, most_common_freqs = {0.6,0.39}, null_frac = 0 and n_distinct = 6. About how many rows will the planner estimate for WHERE kind = 'purchase', and where does that number come from?
Show answer
'purchase' is not an MCV, so the planner uses the leftover fraction divided among the remaining distinct values: (1 - 0.99 - 0) / (6 - 2) = 0.0025. Multiplying by 2,000,000 gives about 5,000 rows. If the real 'purchase' count is far from that, the column has uneven rare values that the MCV list is too short to capture.
Exercise
A query filters on city = 'Paris' AND zip = '75001'. Each condition alone is estimated correctly at 1% of the table, but the combined estimate is 0.01% while the real result is about 1%. Which planner assumption causes this, and what statistics feature addresses it?
Show answer
The planner assumes the two conditions are independent and multiplies their selectivities (0.01 × 0.01 = 0.0001). The columns are strongly dependent, because a zip code determines the city. Extended statistics created with CREATE STATISTICS ... (dependencies) on city, zip let the planner account for that dependency.