Extended Statistics Dependencies And MCV
CREATE STATISTICS with dependencies and mcv records how strongly columns correlate, so the planner stops underestimating conjunctive filters on paired columns.
Code
CREATE TABLE orders_demo (
id int GENERATED ALWAYS AS IDENTITY,
city text NOT NULL,
district text NOT NULL
);
-- city 与 district 完全绑定:三座城市各对应一个固定区
INSERT INTO orders_demo (city, district)
SELECT
(ARRAY['berlin', 'paris', 'tokyo'])[1 + g % 3],
CASE g % 3
WHEN 0 THEN 'mitte'
WHEN 1 THEN '11e'
ELSE 'shibuya'
END
FROM generate_series(1, 20000) AS g;
-- 扩展统计(extended statistics):dependencies 记列间函数依赖,mcv 记组合最频值
CREATE STATISTICS orders_city_district (dependencies, mcv)
ON city, district FROM orders_demo;
ANALYZE orders_demo;
SELECT
statistics_name,
dependencies,
most_common_vals,
most_common_freqs
FROM pg_stats_ext
WHERE statistics_name = 'orders_city_district';How the snippet works
SELECT / INSERT / CREATE statements share the script, touching orders_demo, generate_series and pg_stats_ext.
Breaking the statements into their working parts: a WHERE clause filtering the rows one statement applies to; NOT NULL qualifiers on the required columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Run the statement against the orders_demo table.
Statements that matter
INSERT INTO orders_demo (city, district)
SELECT
(ARRAY['berlin', 'paris', 'tokyo'])[1 + g % 3],
CASE g % 3
WHEN 0 THEN 'mitte'
WHEN 1 THEN '11e'
ELSE 'shibuya'
END
FROM generate_series(1, 20000) AS g;
SELECT
statistics_name,
dependencies,
most_common_vals,
most_common_freqs
FROM pg_stats_ext
WHERE statistics_name = 'orders_city_district';
CREATE TABLE orders_demo (
id int GENERATED ALWAYS AS IDENTITY,
city text NOT NULL,
district text NOT NULL
);
Interactive Tools for This Topic
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.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.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
- Which relations are involved here?
- The references are `orders_demo`, `generate_series`, `pg_stats_ext`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.