One of the production databases I snapshot with dryrun has a 172 GB table that autovacuum analyzes about three times a day. dryrun keeps the planner statistics from every snapshot, so I could line up what pg_stats said about one of its columns over six days in November:

736, 899, 948, 520, 659, 461, 1087, 299

That's n_distinct, the planner's guess at how many different values the column holds. The table grows by a few percent a week, and the guess moved by more than a factor of three. Over sixty days it also went negative 14 times. The column is NULL in 99.8% of the rows.

The cause is one if in analyze.c and the birthday problem, and both show up on a lab table where every row can be counted.

Two tickets in a thousand

The lab is a support desk. Tickets get escalated to an agent now and then, and for the other 99.8% of them escalated_to stays NULL:

CREATE TABLE agents (  id int PRIMARY KEY,  team_id int NOT NULL, -- 20 teams of 100  name text NOT NULL );  CREATE TABLE tickets (  id bigint PRIMARY KEY,  customer_id int NOT NULL,  status text NOT NULL,  created_at timestamptz NOT NULL,  escalated_to int -- agents.id, set on 0.2% of tickets );  CREATE INDEX tickets_escalated_to ON tickets (escalated_to);
 tickets | escalated | agents_used | tickets_per_agent | heap ----------+-----------+-------------+-------------------+--------  10000000 | 20032 | 2000 | 10.0 | 575 MB

agents_used is the number n_distinct should come out as. tickets.customer_id points at a customers table of 200,000 rows and is here as the control, a column in the same table with no NULLs.

Everything was captured on PostgreSQL 18.7 (the postgres:18 image) with autovacuum off, so only my own ANALYZE touches the statistics. setup.sql seeds random(), so the data comes out the same every time, but the seed doesn't reach ANALYZE (three sessions that each ran SELECT setseed(0.1); ANALYZE tickets; got -0.0019, 518 and 949). Your runs will land on different values from the same distribution.

The scripts are setup.sql, analyze-200.sql, experiments.sql and run.sh (with team.sql and summary.sql beside it), and coinflip, a single psql script, counts the plans.

200 runs of ANALYZE

analyze-200.sql runs ANALYZE tickets 200 times in a row and stores what pg_stats reports after each one. Nothing writes to the table in between. distinct_values is how many different estimates the 200 runs produced, and negative how many of them were below zero:

 col | runs | min | max | distinct_values | negative -------------+------+---------------+--------+-----------------+---------- escalated_to | 200 | -0.0025666952 | 2696 | 94 | 75 customer_id | 200 | 183672 | 206763 | 194 | 0

customer_id moves too, since every run is a fresh sample, but it stays within 9% of the true 200,000. The first twelve values for escalated_to, in order:

1247, 2015, -0.0019000173, -0.0018333197, 1957, 1280, 780, -0.0017333627, 1099, 2313, 1844, 485

A negative n_distinct is a fraction of the row count, not a count. -0.0019 on ten million rows claims about 19,000 different agents, and the run right before it said 2,015. On the production table, with twenty-five times the rows, the same fraction claims about 475,000.

Sixty rows and a birthday

ANALYZE does not read every row. With the default default_statistics_target of 100 it samples 30,000 rows (the multiplier of 300 is in analyze.c, and PostgreSQL Statistics walks through how they're picked). Two in a thousand of those rows have an agent, so everything PostgreSQL learns about escalated_to comes from about 60 values. Across my 200 runs the sample held between 42 and 91 of them.

Then comes this, in compute_scalar_stats:

if (nmultiple == 0) {  /*  * If we found no repeated non-null values, assume it's a unique  * column; but be sure to discount for any nulls we found.  */  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac); }

nmultiple is the number of values that showed up more than once in the sample. If none did, the column is declared unique, and the stored value is minus the non-NULL share of the table. That's the -0.0019. For a primary key the rule is exactly right. For this column it turns on whether 60 tickets drawn at random happen to include two for the same agent.

That's the birthday problem with 2,000 possible birthdays. Sixty tickets make 1,770 pairs, which puts a match close to a coin flip. Working the odds out for each run's actual sample size predicts "unique" in 44% of runs. I got 75 of 200, and an earlier batch of 200 on the same data gave 96.

When there is a repeat, PostgreSQL falls through to the Haas-Stokes estimator a few lines further down:

 * n*d / (n - f1 + f1*n/N)  * where f1 is the number of distinct values that occurred  * exactly once in our sample of n rows (from a total of N),  * and d is the total number of distinct values in the sample.

With 60 values and one agent seen twice, that formula gives 1,628. With two agents seen twice it gives 835. One more coincidence halves the answer, so the positive estimates aren't clustered around the truth either; they follow whatever repeats that sample happened to catch. customer_id feeds all 30,000 sampled rows into the same formula, and thousands of repeats average out.

What the planner does with each answer

experiments.sql has a small procedure that repeats ANALYZE until the column lands in the state I want, so both states can be compared side by side. Agent 42 has 11 escalated tickets. After a sample with no repeats:

 Index Scan using tickets_escalated_to on tickets (cost=0.43..8.45 rows=1 width=30)  Index Cond: (escalated_to = 42)

After a sample with repeats (n_distinct came out as 1,425):

 Index Scan using tickets_escalated_to on tickets (cost=0.43..56.53 rows=13 width=30)  Index Cond: (escalated_to = 42)

On its own, a one-row estimate for eleven rows is harmless. It matters once the estimate feeds a join. This is a team lead's view, every escalated ticket for the hundred agents of team 7 with the customer's name:

SELECT a.name, t.id, t.created_at, c.name FROM agents a JOIN tickets t ON t.escalated_to = a.id JOIN customers c ON c.id = t.customer_id WHERE a.team_id = 7

It returns 1,020 rows. When the column is "unique", each agent is expected to match one ticket, and the planner picks nested loops:

 Nested Loop (cost=1.13..900.22 rows=100 width=41) (actual rows=1020.00 loops=1)  Buffers: shared hit=5404  -> Nested Loop (cost=0.71..856.28 rows=100 width=30) (actual rows=1020.00 loops=1)  Buffers: shared hit=1324  -> Index Scan using agents_team on agents a (cost=0.28..10.03 rows=100 width=14) (actual rows=100.00 loops=1)  Index Cond: (team_id = 7)  -> Index Scan using tickets_escalated_to on tickets t (cost=0.43..8.45 rows=1 width=24) (actual rows=10.20 loops=100)  Index Cond: (escalated_to = a.id)  -> Index Scan using customers_pkey on customers c (cost=0.42..0.44 rows=1 width=19) (actual rows=1.00 loops=1020)  Index Cond: (id = t.customer_id)

After a sample with repeats, the inner join becomes a merge join:

 Nested Loop (cost=14.20..1371.55 rows=933 width=41) (actual rows=1020.00 loops=1)  Buffers: shared hit=11091  -> Merge Join (cost=13.78..961.56 rows=933 width=30) (actual rows=1020.00 loops=1)  Merge Cond: (t.escalated_to = a.id)  Buffers: shared hit=7011  -> Index Scan using tickets_escalated_to on tickets t (cost=0.43..477471.90 rows=10000146 width=24) (actual rows=6998.00 loops=1)  -> Sort (cost=13.35..13.60 rows=100 width=14) (actual rows=100.00 loops=1)  Sort Key: a.id  -> Index Scan using agents_team on agents a (cost=0.28..10.03 rows=100 width=14) (actual rows=100.00 loops=1)  Index Cond: (team_id = 7)  -> Index Scan using customers_pkey on customers c (cost=0.42..0.44 rows=1 width=19) (actual rows=1.00 loops=1020)  Index Cond: (id = t.customer_id)

The better estimate picked the plan that reads twice the buffers. The merge join walks tickets_escalated_to in agent order from the first agent up to the last one in the team. Team 7 is agents 601 to 700, so it reads 6,998 tickets to keep 1,020, and the buffer count grows with the team number: 4,888 buffers for team 1, 24,195 for team 20. The nested loop is 5,404 for any of them.

Which plan runs depends on the last ANALYZE, with no deploy and no change in the data. coinflip measures how often. It re-runs ANALYZE on the tables the query reads, plans and executes the query each time, and counts the distinct plan shapes, all inside a transaction that's rolled back:

psql -X -v query="$(cat team.sql)" -v label=default -v runs=40 -v buffers=1 -f coinflip.sql
plans seen:  plan | runs | min_cost | max_cost | min_buffers | max_buffers | shape ------+------+----------+----------+-------------+-------------+--------------------------------------------------  1 | 28 | 983.94 | 1950.15 | 11091 | 11091 | Nested Loop Inner(Merge Join Inner(Index Scan...  2 | 12 | 900.22 | 900.22 | 5404 | 5404 | Nested Loop Inner(Nested Loop Inner(Index Scan...

A nullable foreign key

My first version of setup.sql declared escalated_to int REFERENCES agents, and the team query didn't flip at all. Its estimate also made no sense:

 Merge Join (cost=13.78..961.56 rows=500007 width=18)  Merge Cond: (t.escalated_to = a.id)

With a foreign key between the two join columns the planner skips n_distinct and reasons that every referencing row matches exactly one referenced row, so a hundred agents out of 2,000 get a twentieth of the ten million tickets (including the 99.8% that reference nobody) instead of 1,020. The source admits it, in get_foreign_key_join_selectivity:

 * XXX that's not true in the presence of nulls in the referencing  * column(s), so in principle we should derate the estimate for those.

So a nullable foreign key trades an estimate that changes between runs for one that is stable and 490 times too high. The lab drops the constraint to keep the two effects apart, and experiments.sql adds it back for one EXPLAIN so the number above can be reproduced.

Finding affected columns

Any column that landed in the nmultiple == 0 branch on its last ANALYZE leaves a fingerprint in pg_stats: n_distinct is negative and equals -(1 - null_frac). On a live database, this finds the candidates currently in that state:

SELECT schemaname, tablename, attname, null_frac, n_distinct FROM pg_stats WHERE schemaname NOT IN ('pg_catalog', 'information_schema')  AND null_frac > 0.95  AND n_distinct < 0  AND abs(n_distinct + (1 - null_frac)) < 0.0001 ORDER BY null_frac DESC;

Columns that really are unique (an optional external ID, for instance) match the same filter, so the ones to look twice at are columns you know repeat, like assignees, status codes, or unconstrained ID columns. A column that happened to land in the positive branch on its last ANALYZE won't show up here, so if you already suspect a sparse join column, run ANALYZE on its table three or four times and watch whether n_distinct jumps or flips sign.

For dryrun users: a single snapshot can flag a negative n_distinct, but a positive one looks as plausible as any other. Confirming the wobble takes planner statistics from several snapshots of the same table, compared column by column.

A bigger sample, or no sample

Two per-column settings fix it. The first raises its statistics target, which makes ANALYZE sample 300,000 rows and so about 600 escalated tickets:

ALTER TABLE tickets ALTER COLUMN escalated_to SET STATISTICS 1000;
 label | col | runs | min | max | negative | median_ms -----------+--------------+------+--------+--------+----------+-----------  stats1000 | escalated_to | 200 | 1473 | 2528 | 0 | 624  stats1000 | customer_id | 200 | 197482 | 199241 | 0 | 624

Six hundred values make about 180,000 pairs, so a repeat-free sample stops happening, and coinflip sees one plan in 40 runs. The price is the last column: ANALYZE tickets went from 92 ms to 624 ms, because the sample size for the whole table follows its most demanding column.

The second setting takes the sample out of the question:

ALTER TABLE tickets ALTER COLUMN escalated_to SET (n_distinct = 2000); ANALYZE tickets;

From the next ANALYZE on, pg_stats.n_distinct is 2,000 on every run. A positive override is a fixed count. A negative one scales with the row count (-0.0002 would say one distinct agent per 5,000 tickets), which is the form to use when the number of values grows with the table. Both forms are yours to maintain: if the support team triples, ANALYZE won't notice.

The row estimate for agent 42 still moved between 7 and 13 over 100 runs. It's the non-NULL share of the table divided by n_distinct, and null_frac comes from the same sample (0.9974 to 0.9986 here).

Pinning one column does not freeze the plan's cost either. coinflip again, with the override in place:

plans seen:  plan | runs | min_cost | max_cost | min_buffers | max_buffers | shape ------+------+----------+----------+-------------+-------------+--------------------------------------------------  1 | 40 | 1142.17 | 1853.59 | 11091 | 11091 | Nested Loop Inner(Merge Join Inner(Index Scan...

The histogram on escalated_to and the statistics of the other columns are still resampled on every run.

Between the two, start with SET STATISTICS when you can afford the slower table-wide ANALYZE and 300 * target * (1 - null_frac) puts enough non-NULL rows in the sample to see repeats reliably. It stays accurate as the data changes. Reach for n_distinct when a bigger sample slows autovacuum down too much on a large table (like the 172 GB table from the opening), or when the column is so sparse that even the maximum target of 10,000 leaves too few non-NULL rows.