I have a situation where i need to enforce a unique constraint on a set of columns, but only for one value of a column.
So for example I have a table like Table(ID, Name, RecordStatus).
RecordStatus can only have a value 1 or 2 (active or deleted), and I want to create a unique constraint on (ID, RecordStatus) only when RecordStatus = 1, since I don't care if there are multiple deleted records with the same ID.
Apart from writing triggers, can I do that?
I am using SQL Server 2005.
Best Solution
Behold, the filtered index. From the documentation (emphasis mine):
And here's an example combining a unique index with a filter predicate:
This essentially enforces uniqueness of
ID
whenRecordStatus
is1
.Following the creation of that index, a uniqueness violation will raise an arror:
Note: the filtered index was introduced in SQL Server 2008. For earlier versions of SQL Server, please see this answer.