n_distinct Corrects Group Estimates
ALTER COLUMN SET (n_distinct) corrects planner group-count estimates for skewed columns; negative values mean a fraction of rows.
Code
CREATE TABLE visits (user_id integer, page text);
-- 10 rows contain 2 distinct users; this demo exercises the override itself, not estimation error
INSERT INTO visits
SELECT g % 2, 'home' FROM generate_series(1, 10) AS g;
ANALYZE visits;
-- the planner's n_distinct for user_id under default statistics
SELECT n_distinct FROM pg_stats
WHERE tablename = 'visits' AND attname = 'user_id';
-- explicit override: negative values mean a fraction of table rows, so -0.2 is about 20%
ALTER TABLE visits ALTER COLUMN user_id SET (n_distinct = -0.2);
ANALYZE visits;
-- read pg_stats again: the stored option now drives the group estimate
SELECT n_distinct FROM pg_stats
WHERE tablename = 'visits' AND attname = 'user_id';What the demo overrides
A visits table holds ten rows with two distinct users. The first pg_stats read reports the planner’s n_distinct for user_id as sampled under default statistics; nothing is claimed about accuracy at this size, since the point is the baseline before the override.
ALTER TABLE setting n_distinct to -0.2 then stores the option, and ANALYZE refreshes the statistics so the stored fraction drives the estimate; the second read shows the value derived from that option. Negative values persist as fractions of the table’s row count, so the setting scales as the table grows.
Points worth noting
- Negative n_distinct is a fraction; positive values are absolute counts.
- The reloption survives ANALYZE; sampling never overwrites it silently.
Interactive Tools for This Topic
FAQ
- What does the negative n_distinct value mean?
- A fraction of the table rows: -0.2 tells the planner to expect distinct values equal to about 20% of rows, which the demo stores and then reads back through pg_stats.
Report a problem with this exampleOpens a pre-filled issue on GitHub.