In PostgreSQL 15 and later, what does NULLS NOT DISTINCT change about a unique constraint such as UNIQUE (publisher_id, edition_code), and what must you check before adding it to a live table?
answer
- NULL never equals NULL
- one NULL key column escapes the check
- a clause on the unique index itself
- added in PostgreSQL 15
- the older partial-index workaround
basics
~20 sUnique indexes treat NULLs as distinct by default, so a row with a NULL key column never conflicts. Declaring the constraint or index NULLS NOT DISTINCT (PostgreSQL 15+) makes NULLs compare equal, allowing one (publisher_id, NULL) row per publisher.
solid answer
~40 sBy default PostgreSQL's unique B-tree follows SQL's rule that NULL is not equal to NULL, so `(42, NULL)` can be inserted any number of times; a row conflicts only when every key column is non-NULL and equal to another row's. Since PostgreSQL 15, `UNIQUE NULLS NOT DISTINCT (publisher_id, edition_code)` or `CREATE UNIQUE INDEX ... NULLS NOT DISTINCT` treats NULLs as equal for the uniqueness check, so a second `(42, NULL)` fails with `duplicate key value violates unique constraint` (SQLSTATE `23505`). The flag is stored in `pg_index.indnullsnotdistinct` and only matters on unique indexes. Adding it to a table that already holds such duplicates fails with `could not create unique index`, so find and clean them first. Without the clause, the workaround is a second, partial unique index on `(publisher_id) WHERE edition_code IS NULL`.
code
sql · 16 lines-- find rows that would block the new constraint
SELECT publisher_id, count(*)
FROM books
WHERE edition_code IS NULL
GROUP BY publisher_id
HAVING count(*) > 1;
ALTER TABLE books
ADD CONSTRAINT books_publisher_edition_key
UNIQUE NULLS NOT DISTINCT (publisher_id, edition_code);
INSERT INTO books (category_id, publisher_id, title, price, edition_code)
VALUES (3, 42, 'Dune', 9.99, NULL);
INSERT INTO books (category_id, publisher_id, title, price, edition_code)
VALUES (3, 42, 'Dune (reprint)', 8.99, NULL);
-- ERROR: duplicate key value violates unique constraint "books_publisher_edition_key"go deeper
Recall that unique constraints allow repeated NULLs by default and that NULLS NOT DISTINCT is the clause that changes it.
Explain why the default follows SQL's NULL comparison, how it applies when any key column is NULL, where the flag is stored, and how the partial-index workaround behaves.
Plan the rollout on a live table: find existing duplicates first, build the unique index without blocking writes, and make sure the application handles the new 23505 errors.
Treat a NULL in a business key as a modelling decision: does it mean unknown or none? The answer chooses between NULLS NOT DISTINCT, a sentinel value and a NOT NULL column.
## The default: NULLs never collide A unique index in PostgreSQL checks a new entry against existing entries with the `=` operator of each key column's B-tree operator class. In SQL, `NULL = NULL` is not true, so under the default behaviour, called **`NULLS DISTINCT`**, two NULLs are never considered duplicates. For a multicolumn key the effect is broader than people expect: if **any** key column is NULL, the row cannot conflict with anything. In the bookstore, `edition_code` identifies a publisher's edition and is optional for imported titles. The constraint `UNIQUE (publisher_id, edition_code)` stops two rows of `(42, 'HB-2026')`, but it happily accepts any number of `(42, NULL)` rows, which is usually not what the catalogue team intended when they wrote "at most one edition without a code per publisher". This is standard SQL behaviour, and the NULL storage itself is not the problem: a PostgreSQL B-tree does store NULL entries, which is why `WHERE edition_code IS NULL` can use the index. Only the uniqueness test skips them. ## NULLS NOT DISTINCT PostgreSQL 15 added a clause that flips the comparison for the uniqueness check only: - As a constraint: `ALTER TABLE books ADD CONSTRAINT ... UNIQUE NULLS NOT DISTINCT (publisher_id, edition_code)`. - As an index: `CREATE UNIQUE INDEX ... ON books (publisher_id, edition_code) NULLS NOT DISTINCT`. - In the catalogue, the choice is the boolean **`pg_index.indnullsnotdistinct`**, which is only consulted for unique indexes. With the clause, a NULL in a key column compares equal to another NULL in the same column, so the second `(42, NULL)` is rejected with `duplicate key value violates unique constraint` and SQLSTATE `23505` (`unique_violation`), the same error any duplicate raises. | Rows inserted | Default (`NULLS DISTINCT`) | `NULLS NOT DISTINCT` | |---|---|---| | `(42, 'HB-2026')` twice | Second fails | Second fails | | `(42, NULL)` twice | Both succeed | Second fails | | `(42, NULL)` and `(43, NULL)` | Both succeed | Both succeed | | `(42, NULL)` and `(42, 'HB-2026')` | Both succeed | Both succeed | The clause changes nothing about how queries treat NULL. `WHERE edition_code = NULL` still returns no rows; queries keep using `IS NULL`. ## Before the clause existed: the partial-index workaround On releases before 15, or when the rule for the NULL case differs from the rule for real values, teams pair the normal constraint with a **partial unique index**: 1. Keep `UNIQUE (publisher_id, edition_code)` for rows that have a code. 2. Add `CREATE UNIQUE INDEX ... ON books (publisher_id) WHERE edition_code IS NULL`, which allows only one NULL-code row per publisher. This gives the same guarantee with two indexes instead of one. Its advantage is flexibility: the predicate can carry extra conditions, for example only live listings, which a single `NULLS NOT DISTINCT` clause cannot express. A third pattern, a unique index on `(publisher_id, COALESCE(edition_code, ''))`, also works but has costs: the sentinel `''` collides with a real empty code, and queries must repeat the `COALESCE` expression to use the index. ## Rolling it out on a live table Adding the constraint builds a unique index over existing rows, so it fails if duplicates are already there: - Find them first with a `GROUP BY publisher_id ... HAVING count(*) > 1` over rows `WHERE edition_code IS NULL`. - Decide which duplicates are real data errors and which need a code assigned. - Build the unique index without blocking writes (the concurrent build is covered with index upkeep), then attach it as the constraint if you want one. - Make sure the application treats the new `23505` errors as a business rule, not a crash. If duplicates are left behind, the build stops with `could not create unique index`, and its detail line names a duplicated key. ## Where it does not apply `PRIMARY KEY` columns are always `NOT NULL`, so the clause is irrelevant there. It also has no meaning for non-unique indexes: they do not check duplicates at all. Only B-tree supports unique indexes in PostgreSQL, so this is purely a B-tree feature. To see which existing unique indexes use it, query `pg_index` for `indisunique` and `indnullsnotdistinct`, or read the index definition with `\d books` in `psql`, which prints the `NULLS NOT DISTINCT` clause as part of the index or constraint.
- When would you still choose the partial unique index over NULLS NOT DISTINCT?When the rule for the NULL case is narrower than for real values, for example one uncoded row per publisher only among live listings, the partial index's `WHERE` clause can carry that extra condition. `NULLS NOT DISTINCT` applies one rule to every row. The partial index is also the only option on releases before 15.
- Does NULLS NOT DISTINCT change how WHERE edition_code = NULL behaves?No. It only changes the uniqueness check inside the index. `edition_code = NULL` still yields NULL, so the query returns nothing; you must still write `IS NULL`, which the B-tree can serve. Equality operators and NULL semantics in expressions are untouched.
- A UNIQUE constraint in PostgreSQL rejects a second row with NULL in the key by default.
- NULLS NOT DISTINCT makes WHERE edition_code = NULL return the NULL rows.
- Before PostgreSQL 15 there was no way to allow only one NULL per publisher.
- A unique index on COALESCE(edition_code, '') is equivalent and has no downside.
- Primary key columns need NULLS NOT DISTINCT to stop duplicate NULLs.