In PostgreSQL 18, a delivery_addresses query filtering city = 'Leeds' AND postal_code = 'LS6' estimates 1,200 rows, returns 40,000 and picks a nested loop; how do extended statistics fix it?
answer
- selectivities multiplied as if independent
- error factor equals the city's share
- CREATE STATISTICS, then ANALYZE
- dependencies versus mcv versus ndistinct
- check pg_stats_ext
basics
~20 sThe planner multiplies the two columns' selectivities as if they were independent, so the estimate is too low by exactly the city's share. CREATE STATISTICS (dependencies, mcv) ON city, postal_code FROM delivery_addresses, followed by ANALYZE, shows it that postal_code implies city.
solid answer
~40 sWithout cross-column information the planner multiplies selectivities: 20,000,000 × 0.03 (Leeds) × 0.002 (LS6) = 1,200. But every LS6 address is in Leeds, so the real count is 20,000,000 × 0.002 = 40,000, and the nested loop chosen for 1,200 outer rows runs its inner side 40,000 times. No single-column setting fixes that. `CREATE STATISTICS delivery_addresses_city_postal (dependencies, mcv) ON city, postal_code FROM delivery_addresses;` only records interest; the next `ANALYZE` computes the data from its usual sample. `dependencies` is cheap and covers equality and `IN` with constants, but it assumes the pair is compatible. `mcv` stores real value combinations, so it also handles ranges and impossible pairs, at a higher `ANALYZE` and planning cost. `ndistinct` fixes `GROUP BY city, postal_code` group counts. Check `pg_stats_ext`, then compare estimated and actual rows in `EXPLAIN ANALYZE`.
code
sql · 14 linesCREATE STATISTICS delivery_addresses_city_postal (dependencies, mcv)
ON city, postal_code FROM delivery_addresses;
ANALYZE delivery_addresses; -- the object is empty until this runs
SELECT statistics_name, kinds, dependencies
FROM pg_stats_ext
WHERE tablename = 'delivery_addresses';
EXPLAIN ANALYZE
SELECT a.id, s.tracking_code
FROM delivery_addresses a
JOIN shipments s ON s.address_id = a.id
WHERE a.city = 'Leeds' AND a.postal_code = 'LS6';go deeper
Recall that PostgreSQL multiplies the selectivities of AND-ed filters, and that CREATE STATISTICS exists to describe columns that move together.
Work the 1,200 against 40,000 arithmetic and explain why ANALYZE must run after CREATE STATISTICS before EXPLAIN changes.
Choose between dependencies, mcv and ndistinct for the queries actually misestimated, check pg_stats_ext and EXPLAIN ANALYZE, and know the single-table and virtual-column limits.
Decide how a team finds correlated column pairs worth a statistics object, and weigh the planning and ANALYZE cost of each one against the regressions it prevents.
## Why the estimate is 1,200 PostgreSQL computes a selectivity for each `WHERE` clause from that column's own `pg_stats` row. It then combines `AND`-ed clauses by **multiplying** them, which assumes the columns are independent. On a 20,000,000-row `delivery_addresses` table: 1. `city = 'Leeds'` has selectivity 0.03, or 600,000 rows. 2. `postal_code = 'LS6'` has selectivity 0.002, or 40,000 rows. 3. Multiplied: 20,000,000 × 0.03 × 0.002 = **1,200 rows**. But LS6 is a Leeds postcode district, so every row that matches the postcode also matches the city. The true answer is the postcode's own 40,000 rows, and the underestimate factor is exactly the city's selectivity, 0.03. With 1,200 outer rows expected, the planner chose a nested loop that probes `shipments` by index once per address; at 40,000 real rows that loop dominates the runtime. Per-column settings cannot help. Raising `SET STATISTICS` on either column makes each single-column number more precise and leaves the product just as wrong. ## Extended statistics objects `CREATE STATISTICS` declares interest in a set of columns or expressions of **one table**. `ANALYZE` then computes the multi-column data from the same sample it uses for the single-column statistics. There are three kinds, and leaving the kind list out builds all of them. | Kind | What ANALYZE stores | Improves | Limits | |---|---|---|---| | `dependencies` | how strongly one column determines another, as a coefficient (postal_code ⇒ city near 1.0) | `=` and `IN` with constants | assumes the conditions are compatible; no ranges, `LIKE` or column-to-column comparisons | | `mcv` | the most common value **combinations**, with their frequencies | equality, ranges, impossible pairs | more `ANALYZE`, storage and planning cost; length capped by the object's target | | `ndistinct` | distinct counts for each combination of the listed columns | `GROUP BY city, postal_code` group estimates | does not change `WHERE` estimates | For this query, `dependencies` alone fixes the estimate. With postal_code ⇒ city near 1.0, the planner treats the city clause as redundant and estimates close to 40,000 rows. Adding `mcv` covers what dependencies cannot. Take `city = 'Leeds' AND postal_code = 'M1'`, which matches nothing because M1 is a Manchester district. Dependencies assume the pair is compatible, so they still estimate the size of M1. The MCV list stores real combinations and puts an upper bound on combinations it never saw. ## Creating and checking it ```sql CREATE STATISTICS delivery_addresses_city_postal (dependencies, mcv) ON city, postal_code FROM delivery_addresses; ANALYZE delivery_addresses; SELECT statistics_name, kinds, dependencies FROM pg_stats_ext WHERE tablename = 'delivery_addresses'; ``` `CREATE STATISTICS` takes a `SHARE UPDATE EXCLUSIVE` lock and writes only a catalog entry. Until `ANALYZE`, manual or automatic, runs, the planner has nothing new and `EXPLAIN` still shows 1,200. Confirm the fix with `EXPLAIN ANALYZE`. The estimated rows on the `delivery_addresses` scan should now be close to the actual rows, and a better join method usually follows. `pg_stats_ext` shows one row per object, with `kinds` saying which kinds were built and columns for each result: `dependencies`, `n_distinct`, and `most_common_vals` with `most_common_freqs` and `most_common_base_freqs` for the MCV list. The base frequency is what the per-column statistics alone would predict for a combination, so a large gap between it and the real frequency is the correlation made visible. ## Limits worth knowing - **One table per object.** `CREATE STATISTICS` rejects a second relation, so a correlation between `delivery_addresses.city` and a column of a joined table is invisible to it. - **At most eight** columns or expressions per object, and each column's type needs a default B-tree operator class. - You must **own the table** to create a statistics object on it. - In PostgreSQL 18, **virtual generated columns**, now the default kind of generated column, cannot appear in extended statistics; a `STORED` generated column can. - A major upgrade to 18 with `pg_upgrade` carries regular statistics across but not extended ones. These objects stay empty until the first `ANALYZE` on the new cluster. ## When to create them Create objects for column groups that are **strongly correlated and filtered or grouped together** in queries that are actually misestimated. Every object adds work to each `ANALYZE` of the table and to planning for queries on those columns, so blanket objects on every column pair cost more than they return. The single-expression form, `CREATE STATISTICS ... ON (lower(city)) FROM delivery_addresses`, gives the planner statistics on an expression the way an expression index would, without the index's write cost.
- Why might dependencies statistics alone still misestimate city = 'Leeds' AND postal_code = 'M1' on PostgreSQL's delivery_addresses?Functional dependencies assume the conditions are compatible. Knowing that postal_code determines city, the planner ignores the city clause and estimates the rows for M1, while the true answer is zero because M1 is in Manchester. An `mcv` statistics object stores actual value combinations and gives an upper bound for combinations it never saw, so its estimate for an impossible pair comes out near zero.
- The slow query also filters shipments.carrier_zone, which tracks the delivery city. Can PostgreSQL's CREATE STATISTICS capture that correlation?No. A statistics object covers one table, and PostgreSQL rejects a second relation in `CREATE STATISTICS`. Correlation between columns of two joined tables is still estimated as if they were independent. The options are structural: keep both filter columns in one table, or reshape the query so the correlated filters apply to a single relation.
- Would a composite index on delivery_addresses (city, postal_code) have given PostgreSQL's planner the combined selectivity?No. `ANALYZE` gathers extra statistics for an index only when the index has expression columns. An index on two plain columns adds no joint distribution, and its index conditions are estimated by multiplying the two selectivities as before. The index can make the scan cheaper, but the estimate still needs `CREATE STATISTICS`.
- Raising SET STATISTICS on city and postal_code fixes the correlation misestimate
- CREATE STATISTICS computes the statistics as soon as it runs
- A composite index on (city, postal_code) teaches the planner their correlation
- Functional dependency statistics also correct range filters like postal_code > 'LS'
- Extended statistics also capture correlation between columns of joined tables
Assumes PostgreSQL 18: extended statistics are rejected on its virtual generated columns, and pg_upgrade to 18 carries regular but not extended statistics.