Sub topic 6
How Statistics Become Row Estimates
Assume you know basic SQL, can run psql, and can read simple EXPLAIN output. PostgreSQL uses statistics collected by ANALYZE to estimate how many rows each query step will return. The planner compares those estimates with the cost of possible plans.
The basic calculation
For a filter, the planner estimates:
estimated rows = input rows × selectivitySelectivity is the estimated fraction of input rows that match a condition. For example, if orders contains 100,000 rows and status = 'pending' has a selectivity of 0.05, the estimated result is 5,000 rows.
The estimate affects plan choices:
- A small result may favor an index scan.
- A large result may favor a sequential scan.
- A small join input may favor a nested loop.
- Large inputs may favor a hash join or merge join.
The planner does not usually inspect every row while planning. It reads a compact statistical summary produced by ANALYZE.
Equality predicates and common values
For an equality condition such as status = 'pending', PostgreSQL first checks whether the value appears in the column's most common values, or MCV, list. The list stores frequent values and their observed frequencies.
Suppose statistics contain these values:
| Value | Frequency |
|---|---|
| shipped | 0.95 |
| pending | 0.05 |
For this condition, the planner can estimate approximately 5% of the table:
EXPLAIN
SELECT *
FROM orders
WHERE status = 'pending';The output might contain:
Seq Scan on orders (cost=0.00..1791.00 rows=5000 width=...)
Filter: (status = 'pending'::text)The rows=5000 value is an estimate, not a limit and not a measurement. It describes how many rows the planner expects the scan to emit.
If the searched value is not in the MCV list, the planner estimates its frequency from the remaining values and the distinct-value count. This is less precise when the column contains many unusual values.
Ranges and histograms
For a condition such as customer_id < 100, PostgreSQL uses histogram bounds when available. A histogram divides the non-MCV values into buckets with roughly equal numbers of rows.
If the value 100 falls about one quarter of the way through the histogram's value range, the planner may estimate that about one quarter of the applicable rows match. This assumes values are reasonably distributed between nearby histogram boundaries.
That assumption can fail when values are clustered, have gaps, or change sharply over time. A histogram summarizes a distribution. It cannot preserve every detail.
Nulls are handled separately through null_frac. For example, a predicate using IS NULL can use the stored null fraction directly. Ordinary equality predicates do not match null values.
Combining conditions
For a query with multiple filters, PostgreSQL combines selectivity estimates. Without special information, it often treats conditions as independent.
Suppose the planner estimates:
city = 'Springfield'matches 10% of rows.zip = '12345'matches 1% of rows.
It may estimate the combination as:
0.10 × 0.01 = 0.001That predicts 0.1% of the input. If every row in that city uses that ZIP code, the conditions are correlated and the estimate is far too low.
Extended statistics can record relationships such as dependencies between columns:
CREATE STATISTICS addresses_city_zip (dependencies, ndistinct)
ON city, zip
FROM addresses;
ANALYZE addresses;The planner can then use the relationship instead of multiplying independent guesses.
Compare estimates with reality
Use EXPLAIN (ANALYZE) to execute the query and show actual row counts beside estimates:
EXPLAIN (ANALYZE)
SELECT *
FROM orders
WHERE status = 'pending';Inspect each plan node:
| Plan value | Meaning |
|---|---|
| `rows=5000` | Rows estimated before execution |
| `actual rows=4978` | Rows emitted during execution |
| `loops=1` | Number of times the node ran |
A large, repeated difference suggests stale or insufficient statistics, an unusual distribution, column correlation, or a condition the planner cannot estimate well. Refresh statistics first with ANALYZE. Then consider a higher statistics target or extended statistics.
Exercise
A table has 200,000 rows. The planner estimates that a filter returns 200 rows, but EXPLAIN (ANALYZE) reports 80,000 actual rows. Name two likely causes and one first action.
Show answer
The statistics may be stale or too small to describe the distribution, or multiple filtered columns may be correlated. Run ANALYZE first, then inspect pg_stats and consider a higher statistics target or extended statistics.