CREATE STATISTICS ndistinct Estimates

CREATE STATISTICS (ndistinct) makes ANALYZE collect combined distinct counts for correlated columns, so the planner stops multiplying per-column selectivities.

SqlData Fetching

Code

snippet
-- 两列强相关时,planner 把各列选择率独立相乘会让行数估计(estimates)失真;
-- CREATE STATISTICS 让 ANALYZE 额外收集 (status, priority) 的组合基数
CREATE TABLE tickets (
    id       bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    status   text NOT NULL,
    priority int  NOT NULL
);

CREATE STATISTICS tickets_status_priority (ndistinct)
    ON status, priority FROM tickets;

ANALYZE tickets;

-- 统计对象登记在 pg_statistic_ext:名称与覆盖的列号一目了然
SELECT staname, stxkeys
FROM pg_statistic_ext
WHERE staname = 'tickets_status_priority';

How it works

What runs here is SELECT / CREATE — tickets and pg_statistic_ext are the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; 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

The tickets table is the working surface here.

Statements that matter

SELECT staname, stxkeys
FROM pg_statistic_ext
WHERE staname = 'tickets_status_priority';
CREATE TABLE tickets (
    id       bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    status   text NOT NULL,
    priority int  NOT NULL
);
CREATE STATISTICS tickets_status_priority (ndistinct)
    ON status, priority FROM tickets;

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`tickets`, `pg_statistic_ext` — referenced directly, no join needed.