← Back to SQL, page 2

sql-0037 · Medium mid

Can a column with a UNIQUE constraint hold more than one NULL?

In SQLite, PostgreSQL, MySQL and Oracle, yes: NULLs are not considered equal to each other, so many rows can have NULL in a unique column. SQL Server is the exception and allows only one NULL in a unique constraint. PostgreSQL 15 and later can declare UNIQUE NULLS NOT DISTINCT to allow only one NULL.

Full answer

A unique constraint says no two rows may have equal values. Since NULL = NULL is not true, two NULLs do not violate it on most engines.

A student registry with an optional national ID:

sql
CREATE TABLE registry (id INTEGER PRIMARY KEY, name TEXT, national_id TEXT UNIQUE);
sql
INSERT INTO registry (name, national_id) VALUES ('Ana', NULL), ('Ben', NULL), ('Chen', 'X-77');
SELECT name, national_id FROM registry ORDER BY id;
namenational_id
AnaNULL
BenNULL
ChenX-77

Two students without an ID are accepted. A repeated real value is not:

sql
INSERT INTO registry (name, national_id) VALUES ('Dara', 'X-77');  -- error on purpose
text
Error: UNIQUE constraint failed: registry.national_id

PostgreSQL behaves the same by default. From version 15 you can choose the other rule, and then a second NULL is rejected:

sql
INSERT INTO registry2 VALUES (1, NULL);
INSERT INTO registry2 VALUES (2, NULL);
-- error on purpose
text
Error: duplicate key value violates unique constraint "registry2_national_id_key"

SQL Server's unique constraints treat NULLs as equal and allow only one NULL; a filtered unique index (WHERE col IS NOT NULL) is the usual workaround there. That comes from SQL Server documentation and was not run here.

For a multi-column unique constraint such as (email, deleted_at), the same rule means any row with NULL in either column escapes the check. That is a common way soft-delete designs accidentally allow duplicate active emails. A partial unique index on active rows only is a cleaner design.

sql
CREATE TABLE registry (id INTEGER PRIMARY KEY, name TEXT, national_id TEXT UNIQUE);

INSERT INTO registry (name, national_id) VALUES ('Ana', NULL), ('Ben', NULL), ('Chen', 'X-77');
SELECT name, national_id FROM registry ORDER BY id;

-- error on purpose
INSERT INTO registry (name, national_id) VALUES ('Dara', 'X-77');

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Most engines allow many NULLs in a UNIQUE column
  • SQL Server allows only one NULL in a unique constraint
  • PostgreSQL 15+ offers UNIQUE NULLS NOT DISTINCT
  • NULLs in multi-column unique keys let duplicates slip through

Common mistakes

  • Using a nullable column in a composite unique key and expecting full protection
  • Assuming SQL Server rules apply to PostgreSQL or the reverse

Follow-ups

  • How would you enforce one active email per user with soft deletes?
  • What is a partial index?

Tips

  • Name the SQL Server exception; interviewers often test exactly that