DEV Community

Cover image for What I Learned This Week: Database Constraints
Desiree Lerma
Desiree Lerma

Posted on

What I Learned This Week: Database Constraints

Ruby on Rails is an excellent framework to use. It utilizes object oriented programming, it's flexible, and reads very close to plain old English. One of the great benefits of Rails is that it offers us ActiveRecord for our models (the M in MVC). ActiveRecord is an ORM which allows objects to be mapped to a database. Now that you have a quick overview of what ActiveRecord is I can tell you, we can also add validations to our model because of it. I know, how cool! However, what if I told you, there is another way to limit what data is allowed in? Introducing, DATABASE CONSTRAINTS!

As a heads up, I have been mostly dealing with Postgres as a database so this blog will revolve mostly around Postgres constraints.

Now, back to our regularly scheduled program!

Database constraints are rules you give the database to follow which will allow (or not allow) certain data to be saved or passed through. Constraints can be applied anywhere from the whole schema to one row in a certain table. Listed below are constraints that you can add to your database and why may want to include them your next project or ticket.

  • CHECK: is given an expression and checks it as a boolean. Must not return false.
  • NOT-NULL: values in the column should not evaluate to NULL.
  • UNIQUE: each value in the column with this constraint must be unique.
  • PRIMARY KEYS: values in the column must not evaluate to null and be unique. Remember, primary keys are generally used to identify a record.
  • FOREIGN KEYS: values in the column must reference an existing record in another table (should reference a primary key or a unique constraint).
  • EXCLUSION: any 2 rows compared in column will have at least one return false or null.

Database constraints help to maintain the integrity of your database by helping to keep the data consistent. I read a StackOverflow answer (saved somewhere deep in my bookmarks) that made comparing model validations and database constraints a bit easier to understand, "Database constraints are law; application logic constraints are advice." I hope this blog helps you understand constraints a little bit more!


Top comments (0)