How to create a Unique Index allowing multiple Null Values in SQL Server 2008

by Sumant 1. December 2011 11:43

Problem

I have a column in one of the tables in a SQL Server database where the values must be unique. This column can also contain null values. Now, if I add a unique index on this column, it ensures that all values must be unique in the column (and indexes them too), but, that includes null values too. This means that the column can contain only one null value (at most) i.e. duplicate nulls are not allowed! The problem is how to allow multiple null values in a column with unique index?

Solution

The solution is to use Filtered Index on the column with the filter to allow null values. Filtered Indexes are good for performance as they use a filter predicate to index only a subset of rows in the table. And in this scenario they are also helpful in ignoring null values and indexing rest of the rows.

How to create a Filtered Index to allow multiple Null Values?

CREATE NONCLUSTERED INDEX {Index Name}     
ON {Table} ({column})    
WHERE {column} IS NOT NULL ;
Share   

Tags: ,

MS SQL Server

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

© 2008 Sumant Dubey

About this blog

Absolutely technical! The posts are about concepts, tricks, articles and links on technical subjects / problems which are not very obvious to understand / resolve. Purpose is to have this as the first-aid in the time of need.

RecentComments

Disclaimer

The opinions expressed on this website are my own personal opinions and do not represent my employer's view in anyway.