How to create a unique index on a NULL column? How to create a unique index on a NULL column? sql-server sql-server

How to create a unique index on a NULL column?


Using SQL Server 2008, you can create a filtered index: http://msdn.microsoft.com/en-us/library/cc280372.aspx. (I see Simon added this as a comment, but thought it deserved its own answer as the comment is easily missed.)

Another option is a trigger to check uniqueness, but this could affect performance.


The calculated column trick is widely known as a "nullbuster"; my notes credit Steve Kass:

CREATE TABLE dupNulls (pk int identity(1,1) primary key,X  int NULL,nullbuster as (case when X is null then pk else 0 end),CONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster))


Pretty sure you can't do that, as it violates the purpose of uniques.

However, this person seems to have a decent work around:http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html