CREATE STATISTICS ndistinct Estimates
CREATE STATISTICS (ndistinct) makes ANALYZE collect combined distinct counts for correlated columns, so the planner stops multiplying per-column selectivities.
Code
-- 两列强相关时,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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What objects does the SQL involve?
- `tickets`, `pg_statistic_ext` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.