In SQL Server, how do you keep a nullable column unique among its non-NULL values, and what limits the filtered index that does it?
answer
- how many NULLs UNIQUE tolerates here
- an index with a WHERE clause
- simple predicates joined by AND
- session SET options at write time
basics
~20 sCreate a filtered unique index, CREATE UNIQUE NONCLUSTERED INDEX ... WHERE col IS NOT NULL. Its filter allows only simple comparisons joined by AND, it can't be clustered or use IGNORE_DUP_KEY, and writing sessions need the required SET options.
solid answer
~40 sIn SQL Server a `UNIQUE` constraint lets only one row hold NULL in the column. To allow any number of NULLs while keeping the real values unique, create a **filtered unique index**: `CREATE UNIQUE NONCLUSTERED INDEX UX_Customers_TaxId ON dbo.Customers (TaxId) WHERE TaxId IS NOT NULL;`. Only rows that match the filter must be unique. The filter is deliberately simple: column-to-constant comparisons and `IN` lists joined by `AND`, `IS NULL` or `IS NOT NULL` rather than `= NULL`, and no `OR`, `LIKE` or computed columns. It has to be an index, not a constraint, and it can't use `IGNORE_DUP_KEY`. Any session that modifies those rows needs the required `SET` options, such as `ANSI_NULLS`, `QUOTED_IDENTIFIER` and `ARITHABORT` ON; otherwise its statement fails with error 1934 and is rolled back.
code
sql · 12 linesCREATE TABLE dbo.Customers
(
CustomerId int IDENTITY(1, 1) NOT NULL PRIMARY KEY,
TaxId varchar(20) NULL
);
CREATE UNIQUE NONCLUSTERED INDEX UX_Customers_TaxId
ON dbo.Customers (TaxId)
WHERE TaxId IS NOT NULL;
INSERT dbo.Customers (TaxId) VALUES (NULL), (NULL), ('DE123'); -- succeeds
INSERT dbo.Customers (TaxId) VALUES ('DE123'); -- duplicate key errorgo deeper
Remember that SQL Server's UNIQUE constraint allows a single NULL and that an index can carry a WHERE clause.
Write the filtered unique index, list what its predicate may and may not contain, and explain why it must be an index rather than a constraint.
Anticipate the SET-options failure: which clients and jobs run with QUOTED_IDENTIFIER or ANSI_NULLS off, and what breaks when a table gains a filtered index.
Decide whether optional unique identifiers are enforced in the database with filtered indexes or elsewhere, and make the required session settings a standard for every client that writes.
## SQL Server's single-NULL rule In SQL Server a `UNIQUE` constraint treats NULL like any other value for uniqueness: a single-column unique constraint allows **only one** NULL. Why engines differ here, and what the SQL standard says, is covered with the engine-neutral material on unique constraints and NULLs. On SQL Server the practical problem is common: an optional identifier such as a tax number or an external reference must be unique when it is present, while most rows have none. ## The fix: a filtered unique index A **filtered index** is a nonclustered index with a `WHERE` clause; only rows that match the predicate are stored in it. With `UNIQUE`, only those rows have to be unique: ```sql CREATE UNIQUE NONCLUSTERED INDEX UX_Customers_TaxId ON dbo.Customers (TaxId) WHERE TaxId IS NOT NULL; ``` Any number of rows can now have `TaxId` NULL, because they aren't in the index at all, and a second row with an existing non-NULL value fails with a duplicate-key error. The same pattern enforces "unique among active rows" with a filter such as `WHERE IsActive = 1`. The filtered index also gets **filtered statistics**, which cover only its rows and are more accurate than statistics on the whole table. ## What a filter predicate may contain The grammar is intentionally small: a list of conditions joined by `AND`, where each one compares a column with a constant or tests it against an `IN` list of constants. | Allowed | Not allowed | | --- | --- | | `col = 5`, `col <> 'x'`, `col >= '20250101'` | `OR` between conditions | | `col IN (1, 2, 3)` | `LIKE` | | `col IS NULL`, `col IS NOT NULL` | `col = NULL` (comparison with a NULL literal) | | Several conditions joined by `AND` | Computed, UDT, spatial or **hierarchyid** columns in the filter | | | References to other tables, or anything needing a function on the column | Two more rules catch people: - An implicit or explicit conversion on the **left** side of the comparison is an error (error 10611). Put the `CONVERT` on the constant's side instead, and check that the comparison still means what you intended. - A filter needing more logic belongs in an indexed computed column or an indexed view. ## The SET options trap Filtered indexes depend on session `SET` options. The required values must hold whenever the index is created, whenever an `INSERT`, `UPDATE`, `DELETE` or `MERGE` changes data in the index, and whenever the optimizer uses it: - `ANSI_NULLS`, `ANSI_PADDING`, `ANSI_WARNINGS`, `ARITHABORT`, `CONCAT_NULL_YIELDS_NULL` and `QUOTED_IDENTIFIER` must be **ON**. - `NUMERIC_ROUNDABORT` must be **OFF**. If they're wrong, the index creation fails; a data change that touches the index raises an error and is rolled back (error 1934 says which options are wrong); and the optimizer won't consider the index for that query. The OLE DB and ODBC defaults have `ARITHABORT` OFF, but at database compatibility level 90 or higher `ANSI_WARNINGS` ON implies it. A typical victim is an old client, script or job that sets `QUOTED_IDENTIFIER` or `ANSI_NULLS` OFF and then starts failing on a table that just gained a filtered index. ## Other limits 1. A filtered index must be a **nonclustered** index on a **table**. You can't create one on a view, although queries through a view can still use one on the base table. 2. A filter can't be put on a `PRIMARY KEY` or `UNIQUE` **constraint**; it has to be a `CREATE UNIQUE INDEX`. 3. `IGNORE_DUP_KEY` isn't allowed on a filtered index, and filters don't apply to XML or full-text indexes. 4. A filtered index that holds most of the table can cost more to maintain than a full index. Filtering pays when the subset is small. ## Getting the optimizer to use it The query's `WHERE` clause has to imply the filter, so the optimizer can prove at compile time that every row it needs is in the index. Two column rules follow from the documentation: - A filter column needn't be in the index if the query's predicate is equivalent to the filter and the query doesn't return that column. - It should be a key or included column if the query compares it some other way (`EndDate > '20240101'` against a filter of `EndDate IS NOT NULL`) or returns it. The clustering key is in every nonclustered index anyway, filtered ones included. When a filtered index is used only to enforce uniqueness, none of this matters: the index enforces the rule on every write whether or not any query reads it.
- Which columns should a SQL Server filtered index carry besides its key?A column used in the filter needn't be in the index when the query's predicate is equivalent to the filter and the query doesn't return it. It should be a key or included column when the query compares it some other way or returns it. The clustering key is carried automatically, as in every nonclustered index.
- When is a filtered index a worse choice than a full nonclustered index?When the filter keeps most of the table. A filtered index saves maintenance and storage only when the subset is small; if it holds most rows it can cost more to maintain than a full index, and a full index would also serve queries whose predicates don't match the filter.
- A SQL Server UNIQUE constraint allows any number of NULLs.
- You can add a WHERE clause to a UNIQUE constraint.
- A filtered index predicate can use OR and LIKE like any WHERE clause.
- SET options matter only when the filtered index is created.
- WHERE col = NULL in a filter works the same as IS NULL.