SQL Server – Unique Key Condition Based on Another Value

constraintsql serverunique-constraint

I have a table with the following columns:

ID, STRING_VALUE, ENUM_VALUE, CATEGORY_IDENTIFIER

I'd like to create a condition that won't allow two identical ENUM_VALUEs, but only if their ID is also the same.

For example:

1  BLUE    4  6   --> Good
2  BLUE    4  6   --> Good
3  BLUE    4  6   --> BAD
3  GREEN   4  6   --> BAD

Is there any way to create such a constraint?

Best Answer

Create a unique constraint on the 2 columns.

ALTER TABLE schemaName.tableName ADD CONSTRAINT
        uniTableName UNIQUE NONCLUSTERED
(ID, ENUM_VALUES)