Unique Index Folds NULL With COALESCE

A NULL team_id means the global default; a unique index on COALESCE(team_id, 0), feature makes two NULL-team rows collide exactly like two rows for team 7.

SqlData Integrity

Code

snippet
CREATE TABLE feature_flags (
    team_id  bigint,          -- NULL 表示“全局默认”配置
    feature  text NOT NULL
);

-- 表达式唯一索引:COALESCE 把 NULL 折叠成哨兵 0 参与唯一性判断
-- (多列 UNIQUE 约束本身做不到:NULL 互不相等)
CREATE UNIQUE INDEX flags_key_unique
    ON feature_flags (COALESCE(team_id, 0), feature);

INSERT INTO feature_flags VALUES (NULL, 'dark_mode');
INSERT INTO feature_flags VALUES (7, 'dark_mode');      -- 不同键,成功

DO $$
BEGIN
    INSERT INTO feature_flags VALUES (NULL, 'dark_mode');
    RAISE NOTICE 'second global insert accepted';
EXCEPTION
    WHEN unique_violation THEN
        RAISE NOTICE 'second global insert rejected: %', SQLERRM;
END $$;

SELECT team_id, feature FROM feature_flags ORDER BY team_id NULLS FIRST;

How the snippet works

What runs here is SELECT / INSERT / CREATE — feature_flags are the objects involved.

Mechanically, the statements are built from: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; UNIQUE constraints that keep duplicate values out.

Applying it

The feature_flags table is the working surface here.

Statements that matter

DO $$
BEGIN
    INSERT INTO feature_flags VALUES (NULL, 'dark_mode');
    RAISE NOTICE 'second global insert accepted';
EXCEPTION
    WHEN unique_violation THEN
        RAISE NOTICE 'second global insert rejected: %', SQLERRM;
END $$;
CREATE TABLE feature_flags (
    team_id  bigint,          -- NULL 表示“全局默认”配置
    feature  text NOT NULL
);
CREATE UNIQUE INDEX flags_key_unique
    ON feature_flags (COALESCE(team_id, 0), feature);

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
The references are `feature_flags`.