HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Is it possible to enforce unique values in a column, excluding nulls?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
uniqueenforcecolumnexcludingpossiblevaluesnulls

Problem

I have a business requirement to have a FK field on 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.

CREATE UNIQUE NONCLUSTERED INDEX IX ON TableA(TableBID) WHERE TableBID IS NOT NULL


For 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 NULL

Context

StackExchange Database Administrators Q#36155, answer score: 9

Revisions (0)

No revisions yet.