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.
Code
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
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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Name the tables involved in this file.
- The references are `feature_flags`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.