With SQL Server I want a unique index on only the non-null values
With SQL Server I want a unique index on only the non-null values
275
27-Apr-2023
Updated on 02-Jul-2023
Aryan Kumar
02-Jul-2023Sure. You can create a unique index on only the non-null values in a column in SQL Server using a filtered unique index. A filtered unique index is a unique index that only applies to rows where the specified column is not NULL.
To create a filtered unique index, you use the
CREATE UNIQUE INDEXstatement with theWHEREclause. The syntax for theCREATE UNIQUE INDEXstatement with theWHEREclause is as follows:SQL
For example, to create a unique index on only the non-null values in the
customer_idcolumn in thecustomerstable, you would use the following code:SQL
This will create a unique index on the
customer_idcolumn in thecustomerstable. However, it will only apply to rows where thecustomer_idcolumn is not NULL. This will prevent you from inserting duplicate null values into thecustomer_idcolumn.Here are some additional points to keep in mind when creating a filtered unique index:
WHEREclause must be a Boolean expression that evaluates to TRUE or FALSE.WHEREclause cannot reference any other columns in the index.WHEREclause cannot reference any columns that are not part of the index.WHEREclause cannot reference any columns that are nullable.