Preventing 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 you can create a constraint on your email field that requires its value to match the same regular expression you used in our Rails code. This would prevent non-company email addresses from being inserted ...

Get Rails, Angular, Postgres, and Bootstrap, 2nd Edition 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.