SQL UNIQUE constraint with NULLs
How the unique constraint counts NULL values, engine by engine.
- Kategorie
- Bedingt
- Returns
constraint behaviour- In this category
- 36 of 43
Syntax
CREATE UNIQUE INDEX ... ON t (col) | NULLS NOT DISTINCT
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Different name or syntax | a unique index admits exactly one NULL |
| PostgreSQL | Ja | multiple NULLs by default; NULLS NOT DISTINCT since PG 15 makes them conflict |
| MySQL | Ja | Supported under this name. |
| SQLite | Ja | Supported under this name. |
| Oracle | Ja | Supported under this name. |
Beispiele
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;
Gut zu wissen
- 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.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.