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.

SqlData Integrity

Code

snippet
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

FAQ

Which relations are involved here?
The references are `orders_demo`, `generate_series`, `pg_stats_ext`.