Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 10 / Topic 5 of 9

UNIQUE NULLS NOT DISTINCT

A UNIQUE column, you know. What about its NULLs? By Part 3 logic, NULL ≠ NULL — so classic UNIQUE lets any number of NULLs coexist:

CREATE TABLE gift_cards (
  card_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  code    text UNIQUE
);
INSERT INTO gift_cards (code) VALUES (NULL), (NULL), (NULL);
SELECT count(*) AS null_codes FROM gift_cards WHERE code IS NULL;
CREATE TABLE
INSERT 0 3
 null_codes 
------------
          3
(1 row)

Sometimes that's right ("no code yet", many times over). When it isn't — "at most one pending row per user" patterns — PostgreSQL 15 added the switch:

CREATE TABLE claim_tokens (
  token_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  token    text UNIQUE NULLS NOT DISTINCT
);
INSERT INTO claim_tokens (token) VALUES (NULL);
INSERT INTO claim_tokens (token) VALUES (NULL);
CREATE TABLE
INSERT 0 1
ERROR:  duplicate key value violates unique constraint "claim_tokens_token_key"
DETAIL:  Key (token)=(null) already exists.

Second NULL rejected: the constraint now treats NULLs as equal to each other. One clause, one decision — but only after you've consciously made it.

🧪 Quick quiz — answer from memory, then check.

  1. By default, how many NULLs can a UNIQUE column hold?
  2. What changes that?
Show the answers
  1. Any number — NULLs aren't equal to each other, so they never conflict.
  2. UNIQUE NULLS NOT DISTINCT (PostgreSQL 15+) — then at most one NULL fits.

Done here? The practice set for Part 10 — 6 exercises with solutions — is on the part page.

Search the guide