• Sources: primary
  • Summary: On a 10 million row lab table where escalated_to is NULL in 99.8% of rows, 200 runs of ANALYZE produced 94 different n_distinct values, 75 of them negative, because the 30,000-row sample holds about 60 non-NULL values and compute_scalar_stats declares a column unique when none repeat. The team query flipped between a nested loop at 5,404 buffers and a merge join at 11,091 buffers depending only on the last ANALYZE. SET STATISTICS 1000 stopped the flips at the cost of ANALYZE going from 92 ms to 624 ms, and a fixed n_distinct override pins the estimate.
  • Why it matters: Sparse nullable join columns can change query plans after any autovacuum ANALYZE, and the post gives a pg_stats query to find columns in that state.
  • Background: PostgreSQL's planner estimates join and filter row counts from per-column statistics that ANALYZE builds from a random sample of rows, 300 times the statistics target. n_distinct is stored either as a positive count or, when negative, as a fraction of the row count, so a negative value grows with the table. The post shows that a nullable foreign key makes the planner skip n_distinct and assume every row matches, a stable but far too high estimate.