SET STATISTICS Per Column Sampling

Raise per-column sampling with SET STATISTICS so ANALYZE keeps a longer most_common_vals list and finer histograms for skewed or long-tail columns.

SqlData Fetching

Code

snippet
-- 默认每列只收集 100 个 MCV 与 100 个直方桶;倾斜或长尾列的 estimates
-- 需要更多 sampling 点才够准,planner 才能选对计划
CREATE TABLE clicks (
    click_id  bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    page_slug text NOT NULL
);
INSERT INTO clicks (page_slug)
SELECT 'home' FROM generate_series(1, 9000)
UNION ALL
SELECT 'page-' || g FROM generate_series(1, 1000) g;

-- 提高单列统计目标(0–10000,默认 100)
ALTER TABLE clicks ALTER COLUMN page_slug SET STATISTICS 1000;

-- 必须 ANALYZE 才按新目标重新采样:pg_stats 里 most_common_vals 更长、直方桶更细
ANALYZE clicks;

SELECT n_distinct,
       array_length(most_common_vals::text[], 1) AS mcv_count
FROM pg_stats
WHERE tablename = 'clicks' AND attname = 'page_slug';

-- 恢复系统默认:SET STATISTICS -1,之后同样要 ANALYZE
ALTER TABLE clicks ALTER COLUMN page_slug SET STATISTICS -1;
ANALYZE clicks;

DROP TABLE clicks;

How the snippet works

The file runs SELECT / INSERT / CREATE / ALTER statements, touching clicks, generate_series and pg_stats.

In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects; a UNION combining result sets from separate queries; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Run the statement against the clicks table.

Statements that do the work

INSERT INTO clicks (page_slug)
SELECT 'home' FROM generate_series(1, 9000)
UNION ALL
SELECT 'page-' || g FROM generate_series(1, 1000) g;
SELECT n_distinct,
       array_length(most_common_vals::text[], 1) AS mcv_count
FROM pg_stats
WHERE tablename = 'clicks' AND attname = 'page_slug';
CREATE TABLE clicks (
    click_id  bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    page_slug text NOT NULL
);

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`clicks`, `generate_series`, `pg_stats`.