Question

Is it possible to have a complex Check Constraint?

for example I have a customers table each record of which is assigned a customer type.

therefore I could have several customers with the same type.

I want to set one customer for each type to be the "Primary" account for that type, however only one customer for each type can be Primary.

Is it possible to add a check constraint on the IsPrimary field that checks all customers of the same type to see if there is already one marked as primary?

I can do this in C# code obviously but I would like this as an extra check.

I could also use a trigger but I would like to stick to constraints so that I can handle errors in the same way for all errors.

Thanks

Was it helpful?

Solution

This isn't exactly a check constraint problem. It is a filtered unique index problem.

create unique index customers_type_isprimary on customers(type)
    where isPrimary = 1;

This will guarantee that at most one customer has the isPrimary flag set for each type.

EDIT:

A filtered index is an interesting creation. There are various resources explaining them (such as this), in addition to the documentation.

The idea is to build an index only on rows that match the where clause in the index creation step. One reason to do this is to reduce the size of the index.

Here is a use case with your data structure. You might have a bunch of queries that filter on isPrimary = 1. You never filter on isPrimary = 0 -- you would just leave this out of the where clause. Why clutter up the index with all the unnecessary values? If the predicate is in the query, then the index can be used.

The case of the unique index is more compelling. Filtered unique indexes do exactly what you are asking for -- ensuring that at most one value with IsPrimary is set for each type. It does this by creating an index on type only for customers that have IsPrimary set. The "unique" part of the index guarantees that each type only appears once in the index, and by extension, only one customer can have IsPrimary set for each type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top