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:
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;| name | national_id |
|---|---|
| Ana | NULL |
| Ben | NULL |
| Chen | X-77 |
Two students without an ID are accepted. A repeated real value is not:
INSERT INTO registry (name, national_id) VALUES ('Dara', 'X-77'); -- error on purposeError: UNIQUE constraint failed: registry.national_idPostgreSQL behaves the same by default. From version 15 you can choose the other rule, and then a second NULL is rejected:
INSERT INTO registry2 VALUES (1, NULL);
INSERT INTO registry2 VALUES (2, NULL);
-- error on purposeError: 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.
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