Measured on PostgreSQL 18.4: NULLs bypass UNIQUE and ON CONFLICT DO NOTHING. NULLS NOT DISTINCT, partial indexes, and cleaning duplicates before adding one.
A unique constraint that lets duplicates in
A gift-wrap table at Belgavi's Book Store records, per order line, which wrapping voucher was applied. The rule is one row per order and voucher, and many lines have no voucher at all:
CREATE TABLE gift_wrap (
order_id int NOT NULL,
line_no int NOT NULL,
voucher text,
UNIQUE (order_id, voucher)
);The team expected the constraint to reject a second unvouchered row for the same order. It does not. On PostgreSQL 18.4, inserting (5001, 1, NULL) and then (5001, 2, NULL) succeeds twice and leaves two rows. Inserting the same non-NULL voucher twice fails with SQLSTATE 23505 as expected.
This is standard behaviour, not a bug. In SQL, NULL means unknown, and two unknowns are not known to be equal, so a unique constraint treats NULLs as distinct by default. The PostgreSQL documentation says so in the section on unique constraints. Since PostgreSQL 15 you can ask for the other behaviour explicitly with NULLS NOT DISTINCT. This guide measures what each option does, including the less obvious effect on ON CONFLICT, and shows how to migrate a table that already holds duplicates. Every result below comes from the companion probe postgres_unique_nulls_not_distinct, run against a disposable PostgreSQL 18.4 cluster.
The effect on ON CONFLICT is the dangerous part
Application code often relies on INSERT ... ON CONFLICT DO NOTHING for idempotency: a retried request inserts nothing. With a nullable column in the conflict target, that guarantee silently disappears.
| Scenario | Result on PostgreSQL 18.4 |
|---|---|
Plain UNIQUE (order_id, voucher), two rows with voucher NULL | both inserted, 2 rows |
Same, two rows with voucher WRAP-10 | second fails, SQLSTATE 23505 |
Plain unique, second NULL row with ON CONFLICT (order_id, voucher) DO NOTHING | inserted anyway, 2 rows |
UNIQUE NULLS NOT DISTINCT, two NULL rows | second fails, 23505 |
NULLS NOT DISTINCT, second NULL row with ON CONFLICT ... DO UPDATE SET line_no = EXCLUDED.line_no | the existing row is updated to line 2, 1 row |
The third row is the one that produces duplicate records in production. There is no error and no warning. The conflict is simply never detected, because under the default rule there is no conflict.
Option 1: NULLS NOT DISTINCT
ALTER TABLE gift_wrap
ADD CONSTRAINT gift_wrap_order_voucher UNIQUE NULLS NOT DISTINCT (order_id, voucher);With this clause, NULLs compare equal for the purpose of the constraint, and ON CONFLICT with the same column list detects the conflict. It is the most direct statement of the rule "at most one row per order with no voucher". Note what it implies for multi-column keys: (5001, NULL) and (5001, NULL) collide, and so would (NULL, NULL) twice if the first column were nullable.
The catalog records the choice in pg_index.indnullsnotdistinct. The probe's catalog query lists unique indexes that cover nullable columns, together with that flag, which is a quick audit of a schema:
SELECT c.relname, i.relname AS index_name, x.indnullsnotdistinct,
array_agg(a.attname) FILTER (WHERE NOT a.attnotnull) AS nullable_columns
FROM pg_index x
JOIN pg_class c ON c.oid = x.indrelid
JOIN pg_class i ON i.oid = x.indexrelid
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY (x.indkey)
WHERE x.indisunique AND NOT x.indisprimary
GROUP BY 1, 2, 3
HAVING bool_or(NOT a.attnotnull);Every row with indnullsnotdistinct = false is a place where NULLs can repeat. Some of them are intended, for example an optional external id where many rows have none. The audit is to decide, per row, which is meant.
Option 2: a partial unique index for the NULL case
Before PostgreSQL 15 the common pattern was a second, partial index:
CREATE UNIQUE INDEX gift_wrap_one_unvouchered ON gift_wrap (order_id) WHERE voucher IS NULL;It still works and it is sometimes the better fit, because it states the NULL rule separately from the non-NULL rule. The probe shows a second NULL row failing with 23505, and an idempotent insert succeeding with zero rows when the conflict target names the partial index's predicate:
INSERT INTO gift_wrap VALUES (5001, 3, NULL)
ON CONFLICT (order_id) WHERE voucher IS NULL DO NOTHING;The cost is that every ON CONFLICT statement must choose the right target, and code paths that insert both kinds of rows need two statements or a check first.
Option to avoid: coalesce in an expression index
A third pattern is CREATE UNIQUE INDEX ... (order_id, coalesce(voucher, '')). It treats NULL as the empty string, which means a real empty-string voucher now collides with NULL. In the probe, inserting (5001, 1, NULL) and then (5001, 2, '') fails with 23505. Unless the column can never hold the sentinel, and a CHECK constraint enforces that, this trades one silent bug for another.
Migrating a table that already has duplicates
Adding the constraint to a table with duplicate NULL rows fails with 23505, so find them first. GROUP BY treats NULLs as one group, which is exactly the comparison the new constraint will use:
SELECT order_id, voucher, count(*)
FROM gift_wrap
GROUP BY order_id, voucher
HAVING count(*) > 1;In the probe this returns (5001, NULL, 2). Decide which row survives by a business rule, here the lowest line number, and delete the rest with IS NOT DISTINCT FROM, because = never matches NULL:
DELETE FROM gift_wrap a USING gift_wrap b
WHERE a.order_id = b.order_id
AND a.voucher IS NOT DISTINCT FROM b.voucher
AND a.line_no > b.line_no;After the delete the probe adds the constraint successfully and keeps 2 rows. On a large, busy table, build the index first without blocking writes, then attach it:
CREATE UNIQUE INDEX CONCURRENTLY gift_wrap_nnd_idx
ON gift_wrap (order_id, voucher) NULLS NOT DISTINCT;
ALTER TABLE gift_wrap ADD CONSTRAINT gift_wrap_order_voucher
UNIQUE USING INDEX gift_wrap_nnd_idx;The probe runs the non-concurrent form of the same two steps inside a transaction, because CONCURRENTLY cannot run in one. pg_get_constraintdef then reports UNIQUE NULLS NOT DISTINCT (order_id, voucher), and a second NULL row fails with 23505. A concurrent build that fails partway leaves an invalid index that still takes writes, so check pg_index.indisvalid before attaching. New duplicates can arrive between your cleanup and the index build. The build then fails, and you clean up and retry, so run the cleanup and the build close together.
Decide per column, not per database
Not every nullable column in a unique key is a bug. The default behaviour is right when NULL genuinely means "not known yet" and many rows can be in that state. A partner's external order id, filled in only after the partner confirms, is a good example: a unique constraint on it should allow any number of unconfirmed rows and reject two rows with the same confirmed id. Switching that constraint to NULLS NOT DISTINCT would reject the second unconfirmed order, which is a different bug.
The question to ask for each index the audit lists is what NULL means in that column:
- "None", a real state. No voucher, no gift message, no discount code.
NULLS NOT DISTINCTor a partial index states the rule. - "Not known yet." Leave the default and make sure no idempotent insert relies on that key.
- "Not applicable to this row type." Often a sign that two kinds of rows share a table. A partial unique index per row type is usually clearer than either NULL rule.
Application code deserves the same review. A check-then-insert pattern, a SELECT for an existing row followed by an INSERT if none is found, has a race under concurrency regardless of NULLs. The database constraint is what makes the rule true. With the default NULL behaviour on the key, no constraint enforces it at all.
Tradeoffs
| Approach | Good when | Watch for |
|---|---|---|
NULLS NOT DISTINCT | NULL is one meaningful value, such as "no voucher" | PostgreSQL 15 or later only; multi-column NULL combinations all collide |
| Partial index on the NULL case | the NULL rule differs from the non-NULL rule | every ON CONFLICT must name the right target |
| Make the column NOT NULL with a real value | "none" is a business value | a migration of every reader and writer |
| Leave the default | many rows legitimately have no value | idempotent inserts on that key do not work |
How to verify
Run the catalog audit on each database and record a decision for every listed index. For each index you change, add a test that inserts the NULL case twice and expects 23505, and a test that runs the application's idempotent insert twice and expects one row. The second test is the one that would have caught the original bug.