June 26, 2002 02:26 PM

Multiple NULLs with Unique Constraints

Rating: (0)
SQL Server Magazine
InstantDoc ID #25259

I created a unique constraint on a column called Col1 in table Test1 to enforce uniqueness with the exception of NULL. The entry for "Unique Constraint" in SQL Server Books Online (BOL) specifically says that you can create a unique constraint on columns that allow NULL. However, as soon as I add data and try to enter a second record with NULL in Col1, I receive a message that says I've violated the unique constraint. As I understand unique constraints (as opposed to unique indexes), they allow duplicate NULLS. Am I correct?

...

...This article is for paid Professional Members only.

Already a Professional Member? Please log in now:

NOT A PROFESSIONAL MEMBER? YOU CHOOSE:

Professional Membership

Monthly

Annual

VIP Membership

Monthly

Annual

Add a Comment

Thanks for the tip about "a unique clustered index on the view". Wonderful!

Anonymous User 3/6/2005 9:14:50 AM


Good explanation and very useful

Anonymous User 1/14/2005 5:17:17 AM


Not being a fan of triggers I went looking for other solutions to this problem. As mentioned elsewhere on this site by the MVPs, you can create a view with schemabinding that selects the columns that define your uniqueness constraint and return only the non NULL values in the view. Then create a unique clustered index on the view. (works in Standard Edition SQL Server too). If you have more than one ANSI SQL-92 compliant uniqueness constraint to implement you can create multiple views, each with their own unique clustered index. Alternatively consider creating a computed column that substitutes another unique value in place of a NULL, then place a non clustered index on the computed column(s). For example, to ensure uniqueness on Col2 of type int where Col1 is a primary key of type int you could create the following :
create table Tab1 (
Col1 int not null identity primary key,
Col2 int null,
Col3 as coalesce(Col2, Col1 + 1000000000) UNIQUE
)


Peter Ellis 9/21/2004 7:08:59 PM


You must log on before posting a comment.

Are you a new visitor? Register Here
GOOGLE LINKS
SPONSORED LINKS
FEATURED LINKS