CREATE STATISTICS Fixed a 15,000x Row Estimate Error. Only One Query in Five Changed Plan.
On 3 million rows with perfectly correlated columns, Postgres extended statistics fixed row estimates that were off by up to 15,000x. One query in five changed plan, and some ran slower.
The advice is everywhere. Your query is slow, EXPLAIN ANALYZE shows the planner expected 1 row and got 15,000, the columns in your WHERE clause are related, so run CREATE STATISTICS and the planner will stop guessing. It is good advice, and it is documented. What I wanted to know was how often it changes anything you can feel.
In an earlier Postgres post, a row estimate that was wrong by 150,000 times did no harm on a warm cache.1 That made me suspicious of the fix as much as the problem. So I built the textbook case, three columns that are perfectly correlated, applied every kind of extended statistics to it, and timed five query shapes. The estimates got fixed. The plans mostly did not change, and where they did, the result depended on a memory setting I had not planned to touch.
Why the planner gets this wrong
Before running a query, Postgres estimates how many rows each filter will keep. The fraction kept is the selectivity. For WHERE city = 7 AND zip = 10007 AND state = 7 it looks up the selectivity of each condition from per-column statistics and multiplies them. The documentation states the assumption plainly: the planner “normally assumes that multiple conditions are independent of each other,” and per-column statistics “cannot capture any knowledge about cross-column correlation.”2
If zip determines city, then once you filter on one the other filters nothing more. Multiplying anyway shrinks the estimate by orders of magnitude.
flowchart LR
A["WHERE city = 7<br/>AND zip = 10007<br/>AND state = 7"] --> B["Per-column selectivity<br/>1/2000, 1/2000, 1/50"]
B --> C{"Statistics object<br/>on these columns?"}
C -- no --> D["Multiply<br/>3,000,000 x 1/2000 x 1/2000 x 1/50<br/>= 0.015, shown as rows=1"]
C -- yes --> E["Read stored dependency<br/>or common-value entry<br/>about 1,500 rows"]CREATE STATISTICS stores correlation data for a set of columns you name. There are three kinds, and they target different mistakes:
| Kind | What it records | What the documentation says it fixes |
|---|---|---|
dependencies |
Which columns determine which | Equality conditions (and IN lists) on the dependent columns. Not ranges or LIKE.2 |
ndistinct |
Distinct counts of column combinations | Wrong group counts for GROUP BY a, b.2 |
mcv |
The most common value combinations and their frequencies | Wider range of conditions, and incompatible combinations.3 |
A statistics object does nothing until ANALYZE populates it; every example in the documentation runs one right after creating it.4 The planner also does not use extended statistics for join selectivity estimates,4 a limit that matters later.
The setup
One machine, one Postgres 17.6 server on Windows (the EDB build, default settings except where stated), no other load. A table addr with 3 million rows, about 280 MB, and a table orders with 1.5 million rows and an index on the column that points back to addr.
In addr, city is random from 0 up to N, zip is 10000 + city, and state is city % 50. Two of the columns are functions of the third, which is the most correlated a table can be. I built it three times with N = 2,000, 200 and 20 cities, so the same filter matches 1,553, 14,959 and 158,560 rows. Five queries ran against each:
- Q1: equality on all three columns,
count(pad)so the heap must be read. - Q2:
GROUP BY city, zip, state. - Q3: Q1’s filter joined to
orders. - Q4: the same filter with a
zipthat does not belong to that city, so zero rows match. - Q5: equality on
cityplus aBETWEENrange onzip.
Five variants: no statistics object, then dependencies, ndistinct, mcv, and all three on (city, zip, state). Each variant was rebuilt and re-ANALYZEd in three rounds that cycled through all variants, so a drifting machine cannot favor whichever ran last. Every query ran once to warm up and five more times under EXPLAIN (ANALYZE, TIMING OFF); parallel query and JIT were off. The file cache holds everything, so this is a warm-cache test. The script is linked in the references.5
Result 1: the estimates, fixed unevenly
Show data table
| Actual rows | No statistics | dependencies | ndistinct | mcv | all three | |
|---|---|---|---|---|---|---|
| 2,000 cities | 1,553 | 1 | 1,492 | 1 | 1 | 1 |
| 200 cities | 14,959 | 2 | 14,892 | 1 | 15,200 | 16,100 |
| 20 cities | 158,560 | 425 | 156,213 | 419 | 159,402 | 155,202 |
Without statistics the errors were 1,553x, up to 14,959x (the estimate was 1 in one round and 2 in the others) and about 400x. dependencies fixed all three, every round. It is the only kind that did.
ndistinct never touched Q1, which is what the documentation promises: it is about group counts.2 It did fix Q2. The planner expected about 300,000 groups on the two larger tables (really 2,000 and 200) and 8,000 on the smallest (really 20). With ndistinct it got 2,000, 200 and 20 exactly.
mcv was the odd one. At 20 cities it was exact every round. At 2,000 it never helped. At 200 it helped in five of six ANALYZE runs of the mcv-only variant and in three of six runs of the all-kinds variant, so the same object, on the same data, sometimes produced a useless estimate. The reason is capacity. I inspected the list at 2,000 cities: with the default statistics target of 100 it held 20 combinations (28 in an earlier run), and city 7 was not one of them. After ALTER STATISTICS ... SET STATISTICS 3000 and a fresh ANALYZE, it held all 2,000 and the estimate for the same filter went from 1 to 1,480.6 A most-common-values list can only help for combinations it contains. The documentation says a larger target “will normally result in more accurate extended statistics, as well as more time spent calculating them,”3 but I did not find it stating how many items the list holds.
Two things that did not improve. Q5, the range query, stayed wrong with dependencies (about 2,570 expected against 14,959 at 200 cities), matching the documented equality-only limit.2 And Q4, the combination that cannot exist, got worse: dependencies raised the estimate from about 1 to 1,492, 14,892 and 156,213 rows for a query returning none. The documentation says why: the planner assumes the conditions are “compatible and hence redundant,” and “if they are incompatible, the correct estimate would be zero rows, but that possibility is not considered.”2 The mcv variants kept Q4 at about 1, because the list stores real value pairs.3
Result 2: almost nothing changed plan
Show data table
| No statistics | dependencies | ndistinct | mcv | all three | |
|---|---|---|---|---|---|
| 200 cities, 4 MB | 133.9 | 115 | 135.9 | 123.9 | 116.1 |
| 20 cities, 4 MB | 404.6 | 473.8 | 397.4 | 418.5 | 429.9 |
| 20 cities, 64 MB | 424.7 | 376.9 | 416 | 385.2 | 357 |
Q1, Q4 and Q5 kept the same plan in every variant and every table: a bitmap heap scan fed by two bitmap index scans (Postgres reads two indexes, intersects what they return, then visits only those table pages). Q1 took 3.5 ms, 26 ms and 216 ms on the three tables, with or without statistics, wherever the estimate was fixed or not. An estimate of 1 against 1,553 and an estimate of 1,492 against 1,553 produced the same plan and the same speed.
Q3, the join, is the only place a plan changed. With the old estimate of one or two rows, the planner chose a Nested Loop, probing the orders index once per matching addr row. With an accurate estimate of thousands, it switched to a Hash Join: scan all 1.5 million orders rows, build a hash table from the filtered addr rows, match them. That is sensible when thousands of rows match, and it is where this story turned.
At 200 cities the Hash Join won clearly: 115 ms against 134 ms, with the run ranges (114 to 117 against 131 to 136) not overlapping. At 20 cities, with the default work_mem of 4 MB, it lost. work_mem is the memory a hash table or sort may use before spilling to disk files,7 and the 158,000-row hash table did not fit: the Hash node reported 2 batches, meaning part of the data went through temporary files. The join took 474 ms against 405 ms for the nested loop the estimate error had accidentally preserved. Raise work_mem to 64 MB and the same Hash Join ran in one batch and took 377 ms, against 425 ms for the nested loop. The same plan was 20% faster by changing one setting, and those two ranges (350 to 381 ms against 425 to 502 ms) do not overlap.
So whether the “better” estimate helped depended on work_mem, a number the statistics knew nothing about. I would not read the ordering of the 4 MB bars too finely: the same Nested Loop plan varied by up to 18% between variants in one of my repeat runs (137 to 161 ms), which is the noise floor here. The 20% work_mem effect clears it. The 17% loss at 4 MB does not clearly: its run ranges overlap with the old plan’s, so treat it as “no better, probably worse.”
The second surprise was Q2. The ndistinct object corrected the group estimate from about 300,000 to 200 groups, and the planner kept the same hash aggregate. But the query got slower. (A hash aggregate counts groups by building a hash table with one entry per group.)
| Cities | No statistics | With ndistinct | Hash table peak memory (64 MB runs) |
|---|---|---|---|
| 2,000 | 344 ms | 363 ms (ranges overlap) | not recorded |
| 200 | 334 ms | 379 ms (+14%) | 12,321 kB to 48 kB |
| 20 | 301 ms | 335 ms (+11%) | 409 kB to 24 kB |
The aggregate sized its hash table from the estimate, so the accurate number shrank it by orders of magnitude, and in two of three tables the smaller one was 11 to 14% slower, in both the 4 MB and 64 MB runs. I expected the opposite and I have not found why. I am reporting it as measured, not explained.
What it costs
The statistics objects are cheap to store. They took between 105 bytes (ndistinct) and 3.8 kB (all three) of catalog space. ANALYZE on the 3-million-row table took roughly 0.2 s either way. Planning was the visible cost: the Q1 planning time went from 2.7 ms to between 4.0 and 4.3 ms on the 20-city table with any statistics object present, including ndistinct, which did nothing for that query, and from about 1.5 ms to between 1.5 and 1.9 ms on the larger tables. A millisecond or two per plan will not matter to a report query. It might to a hot path planned thousands of times a second without prepared statements.
What this does not show
All of this is one machine, one Postgres version, a warm cache, and synthetic data where the correlation is perfect. Real columns are looser, and dependencies stores a degree of dependency, so my “fixed within 4%” is the best case. Five query shapes is a small sample, and the ones that benefit from a plan change are joins and aggregations, so a workload heavy in those could look different. The join result in particular depends on the shape of orders; I tested one index layout. Cold storage was not measured. The statistics were refreshed by hand, so I also did not test how they hold up as the table drifts between autovacuum analyses.
One mistake of mine is worth recording. A first run labelled “64 MB” had not applied the setting; I noticed because the Hash node’s peak memory was identical to the 4 MB run. I fixed the script to read work_mem back from the session and abort on a mismatch, discarded that run, and reran. Every 64 MB number here comes from the rerun.5
A routine for deciding whether to bother
- Find the node in
EXPLAIN (ANALYZE)whererows=and the actual rows differ by 10x or more, and ask whether a different plan would be better there. A bad estimate on a node whose plan would not change costs you nothing. - If the columns are related by equality,
dependenciesis the dependable first choice. Check the result with a combination that does not exist. - For
GROUP BYover several columns, tryndistinct, and compare the runtime, not just the estimate. - If you use
mcv, check the list actually contains your values (pg_mcv_list_items) and consider raising the target for that object. - After the estimate is fixed, look at joins. If the new plan is a hash join, check
Hash Batchesin the output. Two or more meanswork_memis the next thing to look at.
Takeaways
dependenciesturned estimates that were wrong by 400x to 15,000x into estimates within 4%, in every round. It is the only kind that did on all three tables.- Fixing the estimate changed the plan for only one query in five (the join). Same plan, same time for the other four.
- The one changed plan was a Hash Join that won by 14% at 200 cities, lost by 17% at 20 cities with default memory, and won by 11% with
work_memat 64 MB. The same plan ran 20% faster at 64 MB than at 4 MB. mcvonly knows the combinations it stores. With 2,000 combinations and the default target it held 20, and my probe value was not among them.- Extended statistics are not free. An
ndistinctobject made one aggregate 11 to 14% slower, and any statistics object added 1.3 to 1.6 ms of planning time on the 20-city table.
References
Footnotes
-
Earlier post, Postgres Wasn’t Ignoring My Index, where an estimate of 1 against 150,000 rows did not hurt a plan on a warm cache. ↩
-
PostgreSQL 17 documentation, Planner Statistics: Extended Statistics, for the independence assumption, the equality-only limit of functional dependencies, the “compatible and hence redundant” assumption, and n-distinct for
GROUP BY. ↩ ↩2 ↩3 ↩4 ↩5 ↩6 -
PostgreSQL 17 documentation, Examples of Multivariate Statistics, for worked examples of dependencies, n-distinct and MCV lists, and the point that an MCV list stores actual values so it can tell which combinations are compatible. The same page and Planner Statistics carry the sentence about a larger statistics target giving more accurate extended statistics at more cost. ↩ ↩2 ↩3
-
PostgreSQL 17 documentation, CREATE STATISTICS, for the three kinds, the default of all kinds when none is listed, and the note that extended statistics are not currently used for join selectivity estimates. ↩ ↩2
-
Measurement script: pg-extended-stats-bench.py, Python 3.12 standard library driving the
psqlCLI. All numbers are direct measurements on PostgreSQL 17.6 (EDB Windows x64 build), default configuration exceptmax_parallel_workers_per_gather = 0,jit = offandwork_memas stated, a 3,000,000-rowaddrtable and a 1,500,000-roworderstable, warm file cache, 1 warm-up plus 5 timed runs per cell, 3 interleaved rounds, measured 2026-11-03. The tables are rebuilt for each city count (--cities 2000,200,20, probe city 7) and the script readswork_memback from the session. ↩ ↩2 -
The
mcvlist inspection usedpg_mcv_list_itemsonpg_statistic_ext_dataafterANALYZE, withdefault_statistics_targetat 100 and thenALTER STATISTICS ... SET STATISTICS 3000, on the 2,000-city table. ↩ -
PostgreSQL 17 documentation, Resource Consumption, for
work_mem(default 4 MB) as the base memory limit for a hash table or sort before spilling, andhash_mem_multiplier(default 2.0). ↩