PostgreSQLDev & Eng

Content type: Hands-on

9 min read

PostgreSQL gets distinct-value estimates wrong in mostly-NULL columns

A detailed study published on the boringSQL blog shows how PostgreSQL's ANALYZE produces unstable n_distinct estimates in columns that are almost entirely NULL, and how this swaps the execution plan without any change to the data.

Article · Dev & Eng
Reading
9 min
Tables
1
Code
7

A detailed study published on the boringSQL blog shows how PostgreSQL's ANALYZE produces unstable n_distinct estimates in columns that are almost entirely NULL, and how this swaps the execution plan without any change to the data.

Editor's note: the list of examples of suspect columns quoted further below ('assignee, status, category') is a free adaptation of the article for the Brazilian context; the original source (boringSQL/Planet PostgreSQL) specifically cites 'assignees, status codes, or unconstrained ID columns'. The central point of the article, about the instability of n_distinct in mostly-NULL columns, is not affected by this difference in examples.

A detailed study published on the boringSQL blog shows how PostgreSQL's ANALYZE produces unstable n_distinct estimates in columns that are almost entirely NULL, and how this swaps the execution plan without any change to the data.

A survey published on the boringSQL blog, and republished on Planet PostgreSQL, exposes a behavior every DBA has felt without being able to name: a query that changes its execution plan from one day to the next, with no change to the data, the indexes, or the version. The culprit, in the case studied, is ANALYZE running on a column where almost everything is NULL.

The author tracked a 172 GB production database whose autovacuum runs ANALYZE about three times a day. Looking at the pg_stats history for a specific column over six days, the n_distinct value oscillated like this: 736, 899, 948, 520, 659, 461, 1087, 299. The table grows a few percentage points per week; the estimate, over the same period, varied by a factor of more than three. Over sixty days, the value also turned negative fourteen times. The column in question is NULL in 99.8% of rows.

A lab to reproduce the problem

To isolate the cause, the author built a help-desk schema where every row can be counted:

sql
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, populated in 0.2% of tickets
);

CREATE INDEX tickets_escalated_to ON tickets (escalated_to);

The table has ten million rows, 575 MB, 2,000 possible agents, and only 20,032 tickets with escalated_to populated. customer_id, in the same schema, is never NULL and serves as a control: it points to 200,000 distinct customers and its n_distinct stays stable.

Everything was reproduced on PostgreSQL 18.7 with autovacuum turned off, so that only manual ANALYZE runs would touch the statistics. Running ANALYZE tickets 200 times in a row on the same data, with no writes between rounds, escalated_to produced 94 different n_distinct values, 75 of them negative. customer_id, in the same experiment, oscillated less than 9% around the real 200,000.

The small sample and the birthday problem

ANALYZE doesn't read the whole table. With the default default_statistics_target of 100, it samples 30,000 rows (the multiplier of 300 is hardcoded in analyze.c). Since only 0.2% of tickets have an agent, that leaves between 42 and 91 non-null values per sample, an average close to 60.

This is where a specific piece of compute_scalar_stats comes in, the function the planner uses for scalar columns:

c
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);
}

If no value repeated in the sample, PostgreSQL assumes the column is unique and writes a negative n_distinct, equal to minus the non-null fraction of the table. For a primary key, this rule is exactly correct. For escalated_to, it depends on pure luck: whether 60 randomly drawn tickets do or don't include two escalated to the same agent.

With 2,000 possible agents and 60 sampled values, that forms 1,770 pairs, which puts the chance of at least one coincidence close to a coin flip. The calculation for the real sample size predicts 'unique' in 44% of runs; the author measured 75 out of 200, and an earlier batch reached 96 out of 200.

When there is repetition, PostgreSQL falls back on the Haas-Stokes estimator a few lines later:

n * d / (n - f1 + f1 * n / N)

where f1 is the number of values seen exactly once in the sample and d is the total number of distinct values in the sample. With 60 values and one agent seen twice, this formula results in 1,628; with two repeated agents, it drops to 835. One coincidence more or less is enough to cut the estimate in half, because the sample is too small for the hits to cancel out, as happens with customer_id, which gets all 30,000 sampled rows and plenty of repetitions to smooth out the result.

The effect on the plan: nested loop becomes merge join

The author isolated the two states using a routine that repeats ANALYZE until it lands on each one, to compare them side by side. Agent 42 actually has 11 escalated tickets. With a sample with no repetitions, the planner estimates one row for this lookup:

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

With a sample that caught repetitions (n_distinct = 1,425), the same lookup estimates 13 rows, close to reality. On its own, getting a single-row estimate wrong breaks nothing. The problem shows up when this column enters a join, like the query a team lead would run to see the escalated tickets of the hundred agents on team 7:

sql
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

The query always returns 1,020 rows, but the chosen plan depends on when the last ANALYZE ran. When the column is marked as 'unique', the planner expects one row per agent and picks nested loops, reading 5,404 buffers. When the sample caught repetitions, the planner estimates 933 rows and switches to a merge join that scans tickets_escalated_to in agent order, reading 6,998 tickets and 11,091 buffers, double the amount. The coinflip tool, built for the experiment, confirms the instability: across 40 repetitions of ANALYZE on the same tables, it saw 28 runs with one plan and 12 with the other, with no change to the data between rounds.

Why a nullable foreign key isn't the answer

The author's first attempt was declaring escalated_to int REFERENCES agents. The plan stopped oscillating, but the estimate also stopped making sense: the merge join started predicting 500,007 rows for a query that returns 1,020. With a foreign key between the join columns, the planner ignores n_distinct and assumes every referenced row matches exactly one source row, spreading the ten million tickets (including the 99.8% with no agent) evenly across the 2,000 possible agents.

PostgreSQL's own source code, in get_foreign_key_join_selectivity, admits the limitation:

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.

In other words: a nullable foreign key trades an estimate that varies with every ANALYZE for a stable estimate that is 490 times larger than reality. Neither one is reliable; the difference is that the second one always fails the same way, which makes it easier to ignore until it really hurts.

How to find suspect columns in your own database

Every column that fell into the nmultiple == 0 branch in the last ANALYZE run leaves a mark in pg_stats: a negative n_distinct equal to -(1 - null_frac). This query locates the candidates:

sql
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 example) also match this filter, so it's worth looking closely only at columns you know repeat: assignee, status, category. A column that fell into the positive branch on the last run doesn't show up in this search, even though it's equally unstable; if you already suspect a sparse join column, run ANALYZE three or four times in a row on the table and watch whether n_distinct jumps in value or flips sign.

Two fixes, with different trade-offs

There are two per-column settings to fix the problem, and they are not interchangeable:

ApproachWhat it doesCost
ALTER TABLE tickets ALTER COLUMN escalated_to SET STATISTICS 1000;Samples 300,000 rows instead of 30,000, capturing about 600 non-null values and practically eliminating the chance of a sample with no repetitionANALYZE on the table gets slower (in the experiment, from 92 ms to 624 ms), because the sample size follows the most demanding column
ALTER TABLE tickets ALTER COLUMN escalated_to SET (n_distinct = 2000);Fixes the value by hand starting from the next ANALYZE, taking sampling out of the equationNeeds to be maintained manually; if the real number of agents triples, ANALYZE won't notice

A positive value in the second option is a fixed count; a negative value (like -0.0002) expresses a fraction that scales with the table's size, useful when the number of distinct values grows along with the rows. The author recommends starting with SET STATISTICS when a slower ANALYZE is tolerable, and reaching for manual n_distinct when the table is too large (like the 172 GB one from the start) or the column is so sparse that even the statistics cap of 10,000 wouldn't fix it.

What the fix doesn't solve

Fixing n_distinct doesn't freeze the cost of the whole plan. Running coinflip again with the value locked at 2,000, the 40 repetitions converge on a single plan shape, but the estimated cost still varies between runs (from 1,142 to 1,853 in the experiment), because the column's own histogram and the statistics of the other columns keep getting resampled on every ANALYZE. The row estimate for a specific agent also kept oscillating between 7 and 13 across a hundred runs, a reflection of the natural variation in sampled null_frac.

The case is a reminder that the execution plan isn't a fixed property of the query: it's a decision recalculated with every new statistic, and sparse columns are exactly where PostgreSQL's default sampling has the least data to get it right. Before hunting for an index or rewriting the query, it's worth checking whether the problem lies in the very statistic feeding the planner.

Translated from the Brazilian Portuguese original · Read the original