Prevent Bad Data Using Check Constraints

If you’ve done any database work at all, you’re no doubt familiar with a “not null” constraint that prevents inserting null into a column of the database.

 CREATE​ ​TABLE​ people (
  id ​INT​ ​NOT​ ​NULL​,
 name​ ​VARCHAR​(255) ​NOT​ ​NULL​,
  birthdate ​DATE​ ​NULL
 );

In this table, id and name may not be NULL, but birthdate may be. Postgres takes the “null constraint” concept much further by allowing arbitrary constraints on fields. Postgres also has support for regular expressions. This means we can create a constraint on our email field that requires its value to match the same regular expression we used in our Rails code. This would prevent non-company email addresses from being inserted ...

Get Rails, Angular, Postgres, and Bootstrap now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.