I have a strong feeling that MS SQL knows I don’t like it. I don’t say it’s a bad database, but sometimes it’s really “interesting”.
OK, so what I faced this time? Let’s start with basic facts. The NULL value in database is a special value. NULL and NULL is again NULL, NULL and False is again NULL and NULL isn’t equal to NULL. Two days ago I was creating a chain of records in database (which isn’t too relationalish, but …) and I needed unique constraint on one column. No problem you may think. So did I. But not in MS SQL.
Check this example:
1> create table test(id int primary key, foo int); 2> create unique index idx_text on test(foo); 3> go 1> insert into test values (1, null); 2> go (1 rows affected) 1> insert into test values (2, null); 2> go Msg 2601, Level 14, State 1, Server X2-001SQLEXPRESS, Line 1 Cannot insert duplicate key row in object 'dbo.test' with unique index 'idx_text '. The statement has been terminated.
What a mess! Looks like somebody in MS SQL engine team thinks NULL == NULL. After some railing, testing on Firebird and asking my friend about Oracle, I googled: https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=299229. Looks like I’m not alone; feeling better. ![]()
Luckily I’m working on MS SQL 2008 and I can use filtered indices. Created unique index with where clause where <column> is not null and I’m done. But boy that was a bitter finding. Hope I’ll not be punched to the face with these basics again in an at least two months.




Pingback: Tweets that mention Unique constraint on MS SQL?! « Jiří {x2} Činčura -- Topsy.com
Pingback: Twitted by mssqlserver
Pingback: Twitted by rohant
#1 by Michal Neuwirth on 26.9.2009 - 22:37
Quote
Jestli se nepletu tak se takto SQL chova minimalne od verze 7. A myslim si, ze ANSI SQL to tak i definuje.
#2 by cincura.net on 26.9.2009 - 23:13
Quote
No nemam primo specifikaci pred sebou. Ale vzhledem k tomu, jak je definovana logika na NULL hodnotach a ze se tak chova Firebird, Oracle i jsem to tak nejak ocekaval
a je to i reportovano, tak bych si porad dovolil tvrdit, ze unique constraint by mel povolovat vice NULL hodnot, ale pouze jednu not-NULL. Lec muzu se mylit.
#3 by pmezard on 30.9.2009 - 13:18
Quote
Start with:
“”"
set ansi_nulls on
go
“”"
#4 by cincura.net on 1.10.2009 - 21:08
Quote
Even with set ansi_nulls on; it doesn’t work for me. Same error.
Looking into BOL, it doesn’t say anything about the unique and nulls, only the nulls comparison in queries etc. (although it’s related).