Unique NULLS NOT DISTINCT Constraint
Treat NULLs as equal inside UNIQUE with NULLS NOT DISTINCT, so a nullable owner column cannot accumulate duplicate unowned rows.
Code
-- Postgres 15+:默认 UNIQUE 视两个 NULL 互不相等,可空组合能重复插入
-- NULLS NOT DISTINCT 把 NULL 也纳入唯一性判断
CREATE TABLE device_registry (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
fingerprint text NOT NULL,
owner_id bigint,
CONSTRAINT owner_fingerprint_unique
UNIQUE NULLS NOT DISTINCT (owner_id, fingerprint)
);
-- ('fp-1', 42) 与 ('fp-1', NULL) owner 不同:两行都能插入
INSERT INTO device_registry (fingerprint, owner_id)
VALUES ('fp-1', 42), ('fp-1', NULL);
-- ('fp-2', NULL) 首次插入成功
INSERT INTO device_registry (fingerprint, owner_id)
VALUES ('fp-2', NULL);
-- 再执行一次上面的 INSERT 会被 owner_fingerprint_unique 拒绝:
-- NULLS NOT DISTINCT 下两个全 NULL 键视为重复What the code does
Several statements share this file — INSERT / CREATE, with device_registry among the objects involved.
Breaking the statements into their working parts: a DISTINCT qualifier that collapses duplicate rows; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Point it at the device_registry table.
Statements that matter
CREATE TABLE device_registry (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
fingerprint text NOT NULL,
owner_id bigint,
CONSTRAINT owner_fingerprint_unique
UNIQUE NULLS NOT DISTINCT (owner_id, fingerprint)
);
INSERT INTO device_registry (fingerprint, owner_id)
VALUES ('fp-1', 42), ('fp-1', NULL);
INSERT INTO device_registry (fingerprint, owner_id)
VALUES ('fp-2', NULL);
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
- What objects does the SQL involve?
- `device_registry` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.