patternsqlMinor
Is it possible to enforce unique values in a column, excluding nulls?
Viewed 0 times
uniqueenforcecolumnexcludingpossiblevaluesnulls
Problem
I have a business requirement to have a FK field on
Is it possible somehow to enforce this type of uniqueness on the DB level, using either an index or a constraint?
TableA referencing TableB. If there is a value in TableBID, it should be unique, but it's not mandatory, so there could be multiple records with null values.Is it possible somehow to enforce this type of uniqueness on the DB level, using either an index or a constraint?
Solution
You can create a unique filtered index as below.
For versions of SQL Server prior to filtered index support (pre 2008) see this related question.
CREATE UNIQUE NONCLUSTERED INDEX IX ON TableA(TableBID) WHERE TableBID IS NOT NULLFor versions of SQL Server prior to filtered index support (pre 2008) see this related question.
Code Snippets
CREATE UNIQUE NONCLUSTERED INDEX IX ON TableA(TableBID) WHERE TableBID IS NOT NULLContext
StackExchange Database Administrators Q#36155, answer score: 9
Revisions (0)
No revisions yet.