Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good to use check constraints for business rules

Currently we are using check constraints for business rules implementation, but I want to know if we should implement business rules in SQL or in the business logic layer (C#). I have searched on the net and found that check constraints are good to use.

Please let me know if someone knows more detailed information about it. One more thing is that the data can be pumped into my database using a mobile application and also using a web application.

like image 592
Punit Avatar asked Nov 11 '09 10:11

Punit


2 Answers

YES it is good!

You should really always check your business rules both in your app code (in the business layer), but if ever possible also in your database.

Why? Imagine someone manages to submit some data to your database without using your app - if you have your checks only in the app, those checks are not being applied.

If you have your checks on the database as well, you can make sure the data in the database conforms to at least those simple checks that can be formulated in SQL CHECK CONSTRAINTS.

Definitely use those! You need to try and keep your data quality as high as possible - adding referential integrity, check constraints and unique constraints and so forth on the database helps you do that.

Do not rely on your app alone!

like image 64
marc_s Avatar answered Sep 19 '22 07:09

marc_s


Yes, check constraints are a valid tool for business rules.

But are you sure you need to use check constraints, or use a supporting table with a foreign key relationship? If you find yourself defining similar check constraints in various places - the answer is yes, this should definitely be a supporting table.

Data integrity is key; there's not much value to a system that will allow a person to store something that is not per business rules if the application is circumvented. It also makes life a lot easier if the logic is in the database for situations where the original app is in C# and the higher-ups decided the market needs a Java/Ruby/Python/etc version.

like image 45
OMG Ponies Avatar answered Sep 22 '22 07:09

OMG Ponies