Unique Constraints on Nullable Columns in SQL Server 2008

In earlier versions of SQL Server when you created a unique constraint on a nullable column, NULL would count as a value and you would only be able to use NULL once.  The workaround for this was to create a trigger that enforced uniqueness for only the non-null values, but that is not necessarily an ideal solution.  Luckily there is a cleaner solution offered in SQL Server 2008 that is also very flexible.   The following is referred to as “filtered indexes” by Microsoft:

CREATE UNIQUE NONCLUSTERED INDEX User_PinNr_IUC
ON [User] (pinNr)
WHERE pinNr IS NOT NULL

That will create a unique index on the User table’s pinNr column but will allow any number of NULL values.  We can extend this further by enforcing uniqueness only for active users:

CREATE UNIQUE NONCLUSTERED INDEX User_PinNr_IUC
ON [User] (pinNr)
WHERE pinNr IS NOT NULL AND isActive = 1

More information on filtered indexes can be found @ Microsoft.

This entry was posted in Development and tagged , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

3 Comments

  1. hm
    Posted May 11, 2010 at 11:07 am | Permalink

    Thanks for this post, it was really helpful!

  2. Matt
    Posted January 26, 2011 at 10:13 am | Permalink

    Exactly what I was looking for. I mean, EXACTLY. Thanks.

  3. Madhuka
    Posted June 3, 2011 at 2:36 am | Permalink

    Nice article, clear & helpful.
    Thanks

One Trackback

  1. [...] rest of this post can be found over at the ProAce Development Blog.  I’ll be doing more writing there from now on but I’ll occasionally link over to [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">