Sub topic 12
How planner statistics drive estimates
This chapter assumes you can read the basic shape of a plan, including the rows= estimate on each node, and that you have run EXPLAIN ANALYZE in psql. It uses PostgreSQL. It explains where the planner gets its row estimates, so you can tell why an estimate is wrong and which fix to try.
Why the planner needs statistics
The planner chooses a plan before it reads any data from your table. To choose, it must guess how many rows each condition will keep. A condition like customer_id = 42 might match 3 rows or 3 million, and the best scan and join strategy differs for each.
PostgreSQL does not scan the table to find out. It reads summaries that were collected earlier. These are the planner statistics. If they are missing, stale or too coarse, the estimates are wrong. Wrong estimates then lead to wrong plan choices, such as a nested loop over millions of rows.
What ANALYZE collects
ANALYZE reads a random sample of each table and stores per-column summaries in the pg_statistic catalog. The pg_stats view presents them in readable form. Table-level counts (reltuples and relpages) are stored in pg_class.
SELECT attname, n_distinct, null_frac
FROM pg_stats
WHERE tablename = 'orders';If the same table name exists in several schemas, add AND schemaname = 'public' (or your schema) to the filter. The view has more columns than this query shows.
| Column in `pg_stats` | Meaning |
|---|---|
| `null_frac` | Fraction of rows where the column is NULL |
| `n_distinct` | Estimated number of distinct values. A negative number is a fraction of the row count, so `-1` means every value is unique |
| `avg_width` | Average size of the column in bytes. This feeds the `width=` value in a plan |
| `most_common_vals` and `most_common_freqs` | The most frequent values (MCVs) and the fraction of rows each one occupies |
| `histogram_bounds` | Boundaries that split the remaining, non-MCV values into buckets of roughly equal row counts |
| `correlation` | How closely the physical row order follows the column order, from -1 to 1 |
The sample size is 300 × default_statistics_target rows. With the default target of 100, that is 30,000 rows, whatever the table size. On a table with 500 million rows, the statistics describe only a tiny slice. This is usually enough, but not for skewed columns with many distinct values.
From statistics to a row estimate
The planner turns each condition into a selectivity, which is the fraction of rows expected to match. The estimated rows are the table's reltuples times the selectivity.
- Equality on a common value. If the value appears in
most_common_vals, the planner uses its recorded frequency directly. - Equality on any other value. The planner assumes the leftover rows are spread evenly over the leftover distinct values. The formula is
(1 - null_frac - sum of MCV frequencies) / (n_distinct - number of MCVs). - Range conditions such as
created_at >= DATE '2026-01-01'. The planner counts the histogram buckets that fall inside the range. It interpolates inside the partial bucket at the edge. IS NULL. The planner usesnull_frac.
This explains a common surprise. Two queries that differ only in the constant can get very different estimates. status = 'shipped' may be an MCV with an exact frequency. status = 'on_hold' is a rare value that falls back to the even-spread guess.
Combining conditions
For WHERE a = 1 AND b = 2, the planner multiplies the two selectivities. This assumes the columns are independent. When they are not, the product is too small and the row estimate is too low.
Take a table with 1,000,000 orders. About 2% are in the city Leeds, and about 0.5% have zip code LS1. Independence gives 1,000,000 × 0.02 × 0.005 = 100 rows. But every LS1 row is in Leeds, so the real count is about 5,000. The plan might look like this (numbers are illustrative):
Index Scan using orders_zip_idx on orders (cost=0.42..412.80 rows=100 width=64) (actual time=0.05..9.8 rows=5000 loops=1)
Index Cond: (zip_code = 'LS1'::text)
Filter: (city = 'Leeds'::text)An estimate off by 50 times at a leaf node is carried upward. A join above it may choose a nested loop that expects 100 inner lookups and performs 5,000.
Fixing correlated columns with extended statistics
By default, statistics are per column. Extended statistics let you describe relationships between columns.
CREATE STATISTICS orders_city_zip_stats (dependencies)
ON city, zip_code FROM orders;
ANALYZE orders;CREATE STATISTICS only defines the object. Data is gathered the next time ANALYZE runs, so the ANALYZE line is required. PostgreSQL offers three kinds:
| Kind | Helps with | Example |
|---|---|---|
| `dependencies` | One column determines another, as with zip code and city | Equality filters on both columns |
| `ndistinct` | Distinct counts of column combinations | `GROUP BY city, zip_code` row estimates |
| `mcv` | Common combinations of values, including range and `OR` conditions | Skewed pairs such as (`Leeds`, `LS1`) |
If you omit the kinds, PostgreSQL builds all of them. Dependencies apply only to equality conditions, and they assume the filter values are consistent with each other. A query asking for city = 'Leeds' AND zip_code = '90210' is not helped, because that combination cannot occur.
Keeping statistics fresh
Statistics describe the table as it was at the last analyze. After a bulk load, a large delete or a big change in value distribution, they can be badly out of date.
Autovacuum runs ANALYZE automatically. It triggers when the number of changed rows exceeds autovacuum_analyze_threshold (default 50) plus autovacuum_analyze_scale_factor (default 0.1) times the row count. On a 100-million-row table, that is about 10 million changed rows before an automatic refresh. Large tables may need a lower scale factor, which you can set per table:
ALTER TABLE orders SET (autovacuum_analyze_scale_factor = 0.01);Run ANALYZE by hand in these cases:
- After a bulk load or a large
UPDATEorDELETE, before running important queries. - After creating an expression index or extended statistics.
- On temporary tables. Autovacuum cannot see them, so they have no statistics unless you analyze them.
To see when a table was last analyzed, query pg_stat_user_tables:
SELECT relname, last_analyze, last_autoanalyze, n_mod_since_analyze
FROM pg_stat_user_tables
WHERE relname = 'orders';Giving a column more detail
If a skewed column is estimated badly even after a fresh ANALYZE, the default 100 buckets and MCV slots may be too few. Raise the target for that column:
ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 1000;
ANALYZE orders;A higher target increases the sample size, the MCV list and the histogram detail. The costs are a slower ANALYZE and slightly more planning time, because the planner must read larger statistics. Raise it for the specific columns that cause trouble. Do not change default_statistics_target for the whole database as a first move.
Estimates the statistics cannot give
Some misestimates cannot be fixed with more or fresher statistics:
- Expressions.
WHERE lower(email) = '[email protected]'has no statistics onlower(email), so the planner falls back to a generic guess. An expression index, or extended statistics on the expression, gives it something to use. - Join conditions across tables. Column statistics do not capture correlation between columns in different tables. Extended statistics work within a single table only.
- Opaque functions and some operators. The planner uses fixed default selectivities.
- Values unknown at plan time. A generic prepared-statement plan cannot use the frequency of the actual parameter.
When statistics cannot help, rewriting the query is the next option. You can also materialize an intermediate result or add an index on the expression.
A diagnostic routine
- Run
EXPLAIN (ANALYZE)and find the lowest node whererows=(estimated) andactual rowsdiffer by a large factor. - Look up the columns in that node's condition in
pg_stats. Checkn_distinct,null_fracand the MCV list against what you know about the data. - Check
last_analyzeandn_mod_since_analyze. If the table has changed heavily, runANALYZEand compare the plan again. - If two filtered columns are related, create extended statistics.
- If one column is skewed, raise its statistics target.
- If the condition uses an expression, index it or rewrite it.
Exercise
A query filters WHERE city = 'Leeds' AND zip_code = 'LS1' on a table with 1,000,000 rows. pg_stats shows 2% of rows have city Leeds and 0.5% have zip code LS1. The plan estimates rows=100, but the actual count is 5,000. Why is the estimate 100, and what is the fix?
Show answer
The planner assumes the two conditions are independent and multiplies the selectivities: 1,000,000 × 0.02 × 0.005 = 100. The columns are actually correlated, because the zip code determines the city. Create extended statistics with CREATE STATISTICS ... (dependencies) ON city, zip_code FROM orders; and run ANALYZE orders;. The planner can then account for the dependency and estimate close to 5,000 rows.