Skip to content
Advertisement

Check Constraint with Filtering Logic

I have a table that has bit column called “Flag” it does not allow NULL. A requirement here is to ALWAYS have Flag=1 set for every Id in the table below but only 1 time per each unique Id and Flag columns combination. At the same time all other rows can be have Flag=0 set multiple times if there are more than 1 entry.

Basically SUM of Flag grouped by ID should always be 1.

I though of unique constraint on the Id and Flag fields but since Flag=0 can be set multiple times for the same combination this cannot be used.

Any suggestions?

— current dataset

— desired outcome

Advertisement

Answer

You are not looking for a check constraint. You want a filtered unique constraint:

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement