Full answer
Sample schema and data:
sql
CREATE TABLE devices (serial_no text UNIQUE, owner text);
CREATE TABLE badges (code text UNIQUE NULLS NOT DISTINCT, owner text);sql
INSERT INTO devices VALUES (NULL, 'Asha'), (NULL, 'Ben'); SELECT count(*) AS null_serials FROM devices WHERE serial_no IS NULL;Output:
text
null_serials
--------------
2
(1 row)sql
INSERT INTO badges VALUES (NULL, 'Asha');PostgreSQL returns:
text
INSERT 0 1sql
INSERT INTO badges VALUES (NULL, 'Ben');Result on PostgreSQL 17:
text
ERROR: duplicate key value violates unique constraint "badges_code_key"Two devices with no serial number are accepted, since the default rule treats each NULL as distinct. The badges table accepts the first NULL code but rejects the second with a unique-violation error naming the constraint. Which behaviour is right depends on meaning: an unknown serial number should not block other unknowns, but a rule such as 'at most one active badge without a code' needs NULLS NOT DISTINCT or, on PostgreSQL 14 and earlier, CREATE UNIQUE INDEX ... ON badges ((code IS NULL)) WHERE code IS NULL.
sql
CREATE TABLE devices (serial_no text UNIQUE, owner text);
CREATE TABLE badges (code text UNIQUE NULLS NOT DISTINCT, owner text);
INSERT INTO devices VALUES (NULL, 'Asha'), (NULL, 'Ben'); SELECT count(*) AS null_serials FROM devices WHERE serial_no IS NULL;
INSERT INTO badges VALUES (NULL, 'Asha');
INSERT INTO badges VALUES (NULL, 'Ben');Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- UNIQUE allows multiple NULLs by default
- NULLS NOT DISTINCT allows only one
- Available from PostgreSQL 15
- Partial indexes emulate it on older versions
- Choose by what NULL means
Common mistakes
- Assuming UNIQUE blocks duplicate NULLs
- Using sentinel strings instead of NULL
Follow-ups
- How would you allow one NULL per customer?
- How do composite unique keys treat NULLs?
Tips
- Mention the version