// conditional reference

SQL UNIQUE constraint with NULLs

How the unique constraint counts NULL values, engine by engine.

Catégorie
Conditionnel
Returns
constraint behaviour
In this category
36 of 43

Syntaxe

CREATE UNIQUE INDEX ... ON t (col) | NULLS NOT DISTINCT

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Different name or syntax a unique index admits exactly one NULL
PostgreSQL Oui multiple NULLs by default; NULLS NOT DISTINCT since PG 15 makes them conflict
MySQL Oui Supported under this name.
SQLite Oui Supported under this name.
Oracle Oui Supported under this name.

Exemples

PostgreSQL

CREATE UNIQUE INDEX ON t (email) NULLS NOT DISTINCT;

SQL Server

CREATE UNIQUE INDEX ux ON t (email) WHERE email IS NOT NULL;

SQLite

CREATE UNIQUE INDEX ux ON t (email) WHERE email IS NOT NULL;

Bon à savoir

  • Standard semantics: NULL is not a value, so NULLs never collide. Unlimited NULL rows in a unique index on MySQL, SQLite, PostgreSQL and Oracle.
  • SQL Server deviates: exactly one NULL is allowed, which surprises porters both ways.
  • PostgreSQL 15+ offers NULLS NOT DISTINCT to make NULLs collide; Oracle and SQLite have no such switch.
  • Composite unique keys split three ways: PostgreSQL (default), MySQL and SQLite exempt any row with at least one NULL; Oracle exempts only all-NULL keys, so (1, NULL) twice violates the constraint; SQL Server treats NULL as a value, so even (NULL, NULL) is allowed once.

Questions about UNIQUE

How many NULLs can a unique column hold?

Unlimited on MySQL, SQLite, PostgreSQL (default) and Oracle; exactly one on SQL Server.

How do I make NULLs count as duplicates?

PostgreSQL 15+: add NULLS NOT DISTINCT. SQL Server already does it for a plain unique index. Elsewhere: a unique index on an expression such as COALESCE(col, sentinel).

How do I allow many NULLs on SQL Server?

Use a filtered unique index: CREATE UNIQUE INDEX ux ON t (email) WHERE email IS NOT NULL.

What about multi-column unique keys?

PostgreSQL, MySQL and SQLite let any row with a NULL in the key through. Oracle rejects a repeated (1, NULL) and only lets all-NULL keys repeat. SQL Server rejects any repeated key, NULLs included.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.