Imagine we have the following table
Users
Field | Type |
---|---|
Id | INT |
Username | NVARCHAR |
Deleted | BIT |
Then imagine we want Username to be unique for non deleted users. Normally we would make a field unique by doing something like this…
This will fail as multiple deleted users can have the same username in our system. To make a constraint that only constrains a subset of data we need to use a filtered index and make that unique, in the example above that looks like this
We can then do this without any errors
It will also successfully error if we try to create a second non deleted user with the same name