skip to content

On a 600-million-row PostgreSQL delivery_addresses table, pg_stats.n_distinct for customer_id is far below the true count; why does ANALYZE miss it, and how do you fix it durably?

level: seniorimportance: nice to knowfreq 28%

answer

  1. distinct counts extrapolate poorly
  2. a bigger target only helps a little
  3. a per-column option, not a statistic
  4. negative value scales with growth
  5. takes effect at the next ANALYZE

basics

~20 s

ANALYZE extrapolates distinct counts from about 30,000 sampled rows, which fails on huge tables. Measure the true ratio once, set ALTER TABLE ... ALTER COLUMN customer_id SET (n_distinct = -0.05), then ANALYZE; later ANALYZEs keep that override.

solid answer

~50 s

The distinct count is the one statistic a sample cannot measure well. At the default target, `ANALYZE` reads about 30,000 of 600,000,000 rows, sees most of the 30,000,000 customers once or not at all, and has to extrapolate. `SET STATISTICS 10000` raises the sample to 3,000,000 rows, still 0.5% of the table, so it may remain far off. The durable fix is the per-column option: `ALTER TABLE delivery_addresses ALTER COLUMN customer_id SET (n_distinct = -0.05);`. A negative value is a fraction of rows that grows with the table; a positive value is a fixed count. It takes effect at the next `ANALYZE`, and every later `ANALYZE`, manual or automatic, stores it instead of its own guess. Until then, `customer_id = 42` is estimated at far too many rows and `GROUP BY customer_id` at far too few groups.

code

sql · 13 lines
sql
-- measure once, off-peak or on a replica
SELECT count(DISTINCT customer_id) AS distinct_customers,
       count(*) AS total_rows
FROM delivery_addresses;

-- 30,000,000 / 600,000,000 = 0.05 distinct values per row
ALTER TABLE delivery_addresses
    ALTER COLUMN customer_id SET (n_distinct = -0.05);
ANALYZE delivery_addresses;

SELECT n_distinct
FROM pg_stats
WHERE tablename = 'delivery_addresses' AND attname = 'customer_id';

go deeper

for a junior

Know that pg_stats.n_distinct is an estimate from a sample and can be wrong on very large tables.

for a middle

Explain how a low n_distinct inflates equality estimates and deflates GROUP BY estimates, and what positive and negative values mean.

for a senior

Measure the true count, choose between a ratio and a fixed count, apply the override and verify it after ANALYZE, without raising targets server-wide.

for a principal

Treat statistics overrides as configuration with an owner: document each one, and set a trigger for re-measuring when the data's growth pattern changes.

## Why the distinct count is the weak statistic `ANALYZE` builds most column statistics well from a modest sample. A value that makes up 3% of the table makes up about 3% of a 30,000-row sample, and histogram edges settle quickly. The **number of distinct values** is different. It has to be extrapolated from how often values repeat inside the sample. Consider a `delivery_addresses` table of 600,000,000 rows holding about 30,000,000 customers. A 30,000-row sample sees most customers once or not at all, so the estimator has very little to work with, and its answer can be off by a large factor; here it is far too low. The `ANALYZE` reference says so directly: the estimate can be quite inaccurate even at the largest statistics target. ## What a wrong n_distinct breaks - **Equality on values outside the MCV list.** The leftover share is divided by `n_distinct` minus the MCV count. A distinct count ten times too low therefore makes `customer_id = 42` look as if it returns ten times as many rows, which can push the planner from an index scan toward a bitmap or sequential scan. - **Grouping.** `GROUP BY customer_id` is estimated to produce far fewer groups than it really does, which distorts the choice of aggregation strategy and its memory estimate. - **Joins.** Equality-join estimates also use each side's distinct count, so the error spreads into join sizes and join order. A worked example makes the size of the error concrete. Suppose `ANALYZE` reports `n_distinct` = 3,000,000 where the truth is 30,000,000, and the MCV list is short enough to ignore. For `customer_id = 42` the planner then expects roughly 600,000,000 / 3,000,000 = 200 rows, while the real figure is about 20. A query that should be a quick index lookup is now costed as ten times more work. In a join, every row of a driving table multiplies that error. ## The options compared | Approach | Effect | Durable? | |---|---|---| | `ALTER COLUMN customer_id SET STATISTICS 10000` | samples up to 3,000,000 rows; better, still extrapolated, slower `ANALYZE` | yes, but may stay wrong | | `ALTER COLUMN customer_id SET (n_distinct = 30000000)` | a fixed count of distinct non-null values | yes; goes stale if customers grow | | `ALTER COLUMN customer_id SET (n_distinct = -0.05)` | distinct = 5% of the current row estimate | yes; scales with the table | | `pg_restore_attribute_stats()` (new in 18) | writes a statistics value directly | no; the next `ANALYZE` recomputes it | | `CREATE STATISTICS ... (ndistinct)` | distinct counts for column **combinations** | does not help a single column | ## Applying the override 1. **Measure the truth once**, off-peak or on a replica: `SELECT count(DISTINCT customer_id), count(*) FROM delivery_addresses;`. 2. **Choose the form.** If distinct values grow in proportion to rows (each new customer adds a few addresses), use the negative ratio: 30,000,000 / 600,000,000 = 0.05, so `-0.05`. If the set of values is fixed, use a positive count. 3. **Set it**: `ALTER TABLE delivery_addresses ALTER COLUMN customer_id SET (n_distinct = -0.05);`. This writes a per-column option to `pg_attribute.attoptions`, takes a `SHARE UPDATE EXCLUSIVE` lock, and leaves the current statistics alone. 4. **Run `ANALYZE delivery_addresses;`**. From then on every `ANALYZE`, manual or automatic, stores the override in place of its own estimate, and `pg_stats.n_distinct` shows -0.05. 5. **Recheck** the misestimated queries with `EXPLAIN ANALYZE`. `n_distinct_inherited` is the companion option for statistics gathered across inheritance children or the partitions of a partitioned table. `ALTER TABLE ... ALTER COLUMN customer_id RESET (n_distinct)` removes the override. ## Keeping it honest An override is a fact you now maintain by hand. If the shape of the data changes, for example a bulk import of guest checkouts with one address each, the ratio drifts and the planner keeps trusting the stale number. Record why the override exists and re-measure when the table's growth pattern changes. Prefer the negative form whenever it is the ratio, not the absolute count, that stays stable. To find every override in a database, look for columns with options set: `SELECT attrelid::regclass, attname, attoptions FROM pg_attribute WHERE attoptions IS NOT NULL;`. Review that list after major data migrations, because an override silently outranks whatever the next `ANALYZE` would have measured.

  • Why not raise default_statistics_target to 10000 for the whole PostgreSQL server instead of using the n_distinct option?
    It multiplies `ANALYZE` time and `pg_statistic` size for every table, because each one is then sampled at up to 3,000,000 rows, and it makes estimation slightly slower. On this table it still samples only 0.5% of the rows, so `n_distinct` can stay wrong anyway. A per-column override costs nothing at `ANALYZE` time and is exact as long as the measured ratio holds.
  • How do you tell a PostgreSQL n_distinct problem from a cross-column correlation problem when a plan misestimates?
    Estimate each filter on its own. If a single-column equality such as `customer_id = 42` is already far off, compare `pg_stats.n_distinct` with a measured count: that is a distinct-count or MCV problem. If each filter alone is about right and only their combination is wrong, the columns are correlated, and the fix is `CREATE STATISTICS`, not `n_distinct`.

  • SET STATISTICS 10000 always yields an accurate n_distinct
  • pg_restore_attribute_stats() pins n_distinct permanently
  • The n_distinct option recomputes pg_stats immediately
  • A positive n_distinct like 0.05 means five percent of rows
  • n_distinct comes from the column's index, so sampling does not matter