I have a table with many records. Column X is nullable and a lot of records have NULL in this column. Can I create a UNIQUE non-clustered index on this column? Aren't those null values violating the unique constraint?
-
What happened when you tried it?Dan Bracuk– Dan Bracuk2013-02-18 03:11:19 +00:00Commented Feb 18, 2013 at 3:11
-
here, >>Click here for DEMO<< uncomment the last line and build the schema again. see what happens.John Woo– John Woo2013-02-18 03:15:34 +00:00Commented Feb 18, 2013 at 3:15
-
How to create a unique index on a NULL column?peterm– peterm2013-02-18 03:16:43 +00:00Commented Feb 18, 2013 at 3:16
-
Check this for workaround - databasejournal.com/features/mssql/article.php/3711501/…rs.– rs.2013-02-18 03:20:24 +00:00Commented Feb 18, 2013 at 3:20
Add a comment
|
1 Answer
If you're on SQL Server 2008 or newer - you can set up a filtered, unique index to exclude / ignore all the NULL values.
CREATE UNIQUE NONCLUSTERED INDEX uixYourIndexName
ON dbo.YourTableName(YourColumnName)
WHERE YourColumnName IS NOT NULL
That would essentially "filter out" all NULL values - not including them into the index at all. Any query that uses the same WHERE clause can use this filtered index to find those rows.
Without the filtered index, you could not create a UNIQUE INDEX on your column since with a UNIQUE index, you're only allowed to have a single row that has NULL in that column.
2 Comments
Captain Prinny
Does this exclude rows with a null value, or exclude null values when creating the index? IE with rows
1, 2, null and 1, 2, null, does this violate the constraint for third column IS NOT NULL or not?marc_s
@CaptainPrinny: the
WHERE clause just skips any rows that match the condition - so here, any row with NULL in the YourColumnName will not be added to the index and cannot be found by using that index