← 中文资源

简体中文版本

n_distinct 修正分组基数估计

偏斜列的默认基数估计会失真,ALTER COLUMN SET (n_distinct) 显式声明:负数表示占表行数比例;ANALYZE 后从 pg_stats 读回验证。

阅读英文原文

实现说明

一个文件里不止一条语句:SELECT / INSERT / CREATE,visits、generate_series 都在涉及之列。

常见问题

它引用了哪些表或 CTE?

visits、generate_series。

核心语句

SELECT n_distinct FROM pg_stats
WHERE tablename = 'visits' AND attname = 'user_id';
INSERT INTO visits
SELECT g % 2, 'home' FROM generate_series(1, 10) AS g;
CREATE TABLE visits (user_id integer, page text);

代码示例

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';