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.

SqlData Integrity

Code

snippet
-- 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

FAQ

What objects does the SQL involve?
`device_registry` — referenced directly, no join needed.