Check constraint that is a field has a particular value ensure that another field must be filled in.

DB time!

So this post regards "normalisation", or lack of, permitting me to be more lazy, and have simpler databases - what's not to like?

I had a DB table "users", and two distinct classes of user:  Adult and Child.  Now the business logic demands that the Adult users have an email address entered, whereas the child user doesn't necessarily need one.

The Boyce-Cod or whatever blah blah method would be to have 2 tables, but that means loads of JOINs, the inability to view the entire user list in one place, and more logic everywhere.

I'd prefer to have 1 table "Users", but how to enforce the business logic above?

So I've discovered a way - using CHECK CONSTRAINTS in MS SQL 2012+




The "redmouse" is a child user, it is optional whether he has a email address or not.



([role]='Adult' AND [emailaddress] IS NOT NULL OR ([role]='Child' AND [emailaddress] IS NOT NULL OR [role]='Child' AND [emailaddress] IS NULL))

Allows me to denormalise to my hearts content and yet retain the rock solid data stability that we all crave.

Similarly above the "childDoB" column is only relevant to "child" users.   For fun what would be the CHECK CONSTRAINT for that rule?





Comments

Popular posts from this blog

How do you fix a roll of aluminium foil once it's started spiralling?

Why does Premiere Pro "Sequence from clip" on MP4 and then "Match Sequence" result in a massive AVI file?

Churchill's Reaction to Eisenhower's Speech at the English Speaking Union 1951