— The stack

The duplicate your UNIQUE constraint still allows

A runnable PostgreSQL fixture shows why nullable unique columns admit duplicates, how to choose the right invariant, and how to migrate safely.

6 min readUpdated 2026-11-10By Aryan Singh Pokharia, Founding Member & Lead Developer
The duplicate your UNIQUE constraint still allows — conceptual technical diagramAptixLabs · 2026-11-10

Editorial diagram with illustrative states; no customer data. View full-size diagram

A unique constraint can be working exactly as designed while the product still receives records it considers duplicates. In PostgreSQL, a conventional UNIQUE constraint allows multiple NULL values. Before changing the index, decide what “missing” means in the business rule: unlimited unknown values, at most one unknown value, or no unknown values at all.

Write the invariant before changing SQL

Imagine a tenant-scoped external account reference. If the reference is optional during onboarding, many pending rows may legitimately have no value. Enforcing a single NULL per tenant would block normal onboarding. A different table—one primary active configuration per tenant—might legitimately allow at most one missing slot. Those are different product rules, even when both columns are nullable.

Synthetic decision fixture
RuleDatabase shapeExpected duplicate result
Many pending rows without a referenceUNIQUE (tenant_id, external_ref)Multiple NULL references allowed
Only one missing reference per tenantUNIQUE NULLS NOT DISTINCT (tenant_id, external_ref)Second NULL for the same tenant rejected
Reference required for every rowNOT NULL plus UNIQUEMissing reference rejected immediately

Reproduce the surprising default

CREATE TEMP TABLE account_links (
  tenant_id integer NOT NULL,
  external_ref text,
  UNIQUE (tenant_id, external_ref)
);
INSERT INTO account_links VALUES (7, NULL), (7, NULL);
SELECT tenant_id, external_ref, count(*)
FROM account_links GROUP BY tenant_id, external_ref;

The final query returns a count of two for the synthetic tenant. The unique constraint has not failed: PostgreSQL treats the two NULLs as distinct for this constraint. A blank string is different from NULL and would collide with another blank string. Normalize input deliberately; do not silently turn one into the other.

Use NULLS NOT DISTINCT only for the rule that needs it

CREATE TEMP TABLE tenant_slots (
  tenant_id integer NOT NULL,
  slot_key text,
  CONSTRAINT tenant_slots_one_key
    UNIQUE NULLS NOT DISTINCT (tenant_id, slot_key)
);
INSERT INTO tenant_slots VALUES (7, NULL);
-- A second (7, NULL) now violates tenant_slots_one_key.

PostgreSQL documents NULLS NOT DISTINCT for unique constraints in current versions. Check the actual server version before choosing this syntax; PostgreSQL 15 introduced the feature. A partial unique index can instead enforce a rule only for a subset of rows, such as active records. It does not mean the same thing as treating every NULL as equal.

Find existing collisions before migration

SELECT tenant_id, external_ref, count(*)
FROM account_links
GROUP BY tenant_id, external_ref
HAVING count(*) > 1;

Run the grouping check on a production-sized copy before replacing the constraint. Decide which row survives and how references to the others move. Record counts and sample identifiers before and after cleanup. A new constraint cannot validate a table that already violates the chosen rule. Keep the application write path coordinated with the cleanup so a concurrent insert does not recreate the collision.

Test the write paths, not just the schema

Exercise two simultaneous inserts for the same tenant, an upsert with a missing key, and a move from NULL to a real reference. Upsert conflict handling must target the actual unique constraint or matching index. Log the constraint name in failure diagnostics and return an application message that describes the conflict without exposing another tenant’s row.

PostgreSQL constraint documentation

Related: partial unique indexes for archived names

Discuss a data integrity review with AptixLabs

Why does PostgreSQL allow two rows with the same nullable unique key?

A normal UNIQUE constraint treats NULL values as distinct. PostgreSQL 15 and later can use UNIQUE NULLS NOT DISTINCT when the business rule says two missing values should conflict.

Can I use NOT NULL instead?

Yes, if every row must have a reference. NOT NULL expresses a different rule and rejects missing values rather than allowing a single missing value.

Will adding NULLS NOT DISTINCT clean existing duplicates?

No. Resolve conflicting rows and coordinate writers before applying the new constraint.

Need help with b2b saas development for connected customer workflows?

Tell us about your product, existing stack and the problem you need to solve. We can discuss integration scope, implementation tradeoffs and a practical first milestone.

Start a conversation