Sub topic 11
Extended statistics for correlated columns
This chapter assumes you have read the earlier chapters on ANALYZE, pg_stats, and selectivity estimation. You should be comfortable comparing estimated and actual rows in EXPLAIN ANALYZE.
The independence assumption
For a query with several conditions on one table, the planner estimates each condition separately using the per-column statistics in pg_stats. It then multiplies the selectivities. Multiplying is correct only if the columns are statistically independent.
Real data often breaks that assumption. A zip code determines a city. A car model determines its make. A country column constrains a currency column. When two columns are correlated, the product of their selectivities is too small, so the planner underestimates the row count. A plan that looks right for 2 rows can be very slow for 100 or 100,000.
Per-column statistics cannot fix this. Raising the statistics target improves each column's own picture, but the planner still has no information about how the columns relate. Extended statistics supply that information. You create them with CREATE STATISTICS.
Reproducing a misestimate
This script builds a table where zip fully determines city. Each of the 1000 zip codes belongs to exactly one of 51 cities.
CREATE TABLE addresses (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
city text NOT NULL,
zip text NOT NULL
);
INSERT INTO addresses (city, zip)
SELECT 'city_' || (z / 20), lpad(z::text, 5, '0')
FROM (SELECT (random() * 999)::int + 1 AS z
FROM generate_series(1, 100000)) AS s;
ANALYZE addresses;
EXPLAIN (ANALYZE)
SELECT * FROM addresses
WHERE city = 'city_7' AND zip = '00150';Zip 00150 belongs to city_7, so the city condition removes no rows. About 100 rows match, because each zip holds roughly 1/1000 of the table. The output looks approximately like this:
Seq Scan on addresses (cost=0.00..2137.00 rows=2 width=...) (actual time=... rows=98 loops=1)
Filter: ((city = 'city_7'::text) AND (zip = '00150'::text))The exact numbers vary from run to run. The shape is what matters. The planner estimates about 2 rows because it multiplies roughly 1/51 for the city by roughly 1/1000 for the zip. The true count is near 100.
Creating extended statistics
The CREATE STATISTICS command names a set of columns on one table and the kinds of statistics to collect.
CREATE STATISTICS addresses_city_zip (dependencies, ndistinct)
ON city, zip FROM addresses;
ANALYZE addresses;Creating the object does not fill it. The data is computed by the next ANALYZE, whether you run it or autovacuum does. Until then the planner behaves as if the object did not exist. After the ANALYZE, run the same EXPLAIN (ANALYZE) again. The estimate should rise to roughly 100.
Extended statistics have these basic rules:
- They belong to one table. They never describe columns in different tables, so they cannot fix join-correlation errors directly.
- You need at least two columns (or expressions) in the definition.
- You must own the table to create them.
DROP STATISTICS addresses_city_zip;removes one.
The statistic kinds
| Kind | What it stores | What it improves | Minimum version |
|---|---|---|---|
| `ndistinct` | Distinct-value counts for each combination of the listed columns | Group-count estimates for `GROUP BY` and `DISTINCT` on several columns | 10 |
| `dependencies` | How strongly one column's value determines another's | Estimates for equality conditions on the dependent columns | 10 |
| `mcv` | A multi-column list of the most common value combinations with frequencies | Estimates for conditions on common combinations, including ranges and inequalities | 12 |
| `expressions` | Statistics for an expression, such as `lower(email)` | Conditions on an expression that has no index on it | 14 |
If you omit the kind list, PostgreSQL builds all the kinds that apply to the column list.
ndistinct
Without it, the planner estimates the group count for GROUP BY city, zip by combining per-column distinct counts. This often overshoots badly when the columns are correlated. A wrong group count can push the planner toward a hash aggregate that spills to disk, or away from one that would fit in memory. The ndistinct kind fixes that estimate. It does not affect WHERE clause estimates.
dependencies
A functional dependency of zip on city means that once you know the zip, the city adds no information. ANALYZE measures a degree between 0 and 1 for each direction. When the planner sees equality conditions on both columns, it uses the degree to avoid multiplying selectivities for the dependent column.
Here the dependency from zip to city is near 1. The reverse, from city to zip, is weak, because a city has many zips.
Dependencies have a known blind spot. The planner assumes the query's values are consistent with the data. Suppose you ask for city = 'city_1' AND zip = '00150', a combination that does not exist. The planner still estimates about 100 rows, and the real answer is 0. Dependencies are also meant for equality conditions, and the planner applies them to other condition shapes with less reliability.
mcv
An mcv list stores actual combinations, so it handles both blind spots. It knows that ('city_1', '00150') is not present among the common combinations. The cost is size and coverage. The list is limited by the statistics target, 100 entries by default. In the addresses table there are 1000 distinct pairs, so the list covers only the 100 most common. Dependencies describe the whole table with a single number. For high-cardinality combinations like this one, dependencies fits better. For a few dominant combinations, such as (status, region), mcv fits better.
CREATE STATISTICS orders_status_region (mcv)
ON status, region FROM orders;expressions
Since version 14, CREATE STATISTICS accepts expressions, which gives the planner statistics on a computed value without creating an index.
CREATE STATISTICS users_email_lower (expressions)
ON (lower(email)), signup_country FROM users;Expression statistics matter when a query filters on lower(email) = '...'. Without them, the planner falls back to a default guess for the expression's selectivity.
Inspecting what was collected
The pg_stats_ext view shows the contents in readable form. The underlying catalogs are pg_statistic_ext, which holds the definition, and pg_statistic_ext_data, which holds the data and is restricted to superusers.
SELECT statistics_name, attnames, kinds, n_distinct, dependencies
FROM pg_stats_ext
WHERE tablename = 'addresses';The dependencies column prints entries like "3 => 2": 1.0. The numbers are column positions from pg_attribute, so 3 => 2 means column 3 (zip) determines column 2 (city). A degree near 1 is strong. A weak one, such as 0.05 for city => zip, adds little.
Choosing what to create
Do not create extended statistics for every column pair. Each object adds time to ANALYZE and adds planning work, because the planner must examine matching statistics objects for every query on the table. Create them where you have evidence.
A practical rule is to start with the most targeted kind for the symptom, then re-check. Add more kinds only if the estimate is still wrong.
Common errors
- Forgetting
ANALYZE. The statistics object exists but holds no data, so the estimate does not change. Check thatpg_stats_extreturns a row with non-null values. - Expecting join help. A misestimate caused by correlated columns in different tables is not fixed by this feature.
- Mismatched conditions. Extended statistics apply only when the query references the covered columns. A statistics object on
(city, zip)does not help a query that filters oncityandstate. - Using inconsistent values with
dependencies. The planner assumes your condition values go together. When they do not, you get an overestimate. Usemcvfor that case. - Ignoring staleness. Extended statistics are refreshed only when the table is analyzed. A table with heavy churn needs a tuned autoanalyze threshold, such as
autovacuum_analyze_scale_factoron the table. - Raising the wrong target. The per-column
SET STATISTICSvalue does not control the sample for an extended statistics object. Since PostgreSQL 13 you can set it withALTER STATISTICS addresses_city_zip SET STATISTICS 500;. Without that, the object uses the largest target among its columns, or the default.
Verifying the effect
After creating the object and running ANALYZE, compare these three things:
- The estimated rows on the filtered node before and after.
- The plan shape, such as whether a join order or a join method changed.
- The execution time of the real query, not only its estimate.
A better estimate does not always yield a faster query. It yields a plan chosen on correct information, which is the goal of the feature.
Exercise
A table shipments(origin_country, carrier, destination_country) has a query SELECT origin_country, carrier, count(*) FROM shipments GROUP BY origin_country, carrier. EXPLAIN ANALYZE shows the planner expects 40,000 groups but only 300 occur, because each carrier serves only a few countries. Which extended statistics kind addresses this, and what must you run afterward for it to take effect?
Show answer
Create a statistics object with the ndistinct kind on (origincountry, carrier), for example `CREATE STATISTICS shipmentsorigincarrier (ndistinct) ON origincountry, carrier FROM shipments;. Then run ANALYZE shipments;` (or wait for autoanalyze), since the object is empty until the next analyze. The kind is ndistinct because the error is in a group-count estimate, not in a WHERE selectivity.
Exercise
After creating a dependencies statistics object on (city, zip), the query WHERE city = 'city_1' AND zip = '00150' is still estimated at about 100 rows, but it returns 0 rows. Why does this happen, and which kind handles it better?
Show answer
The dependencies kind assumes the queried values are consistent with the data's dependency, so it treats the city condition as redundant given the zip. It does not know that this particular pair never occurs. An mcv statistics object stores actual value combinations, so it can recognize a pair that is absent from the common combinations. It is limited by the statistics target, so it covers only the most common pairs.