Constraints

Let's learn about the database constraints to keep invalid data out of the database.

Keeping invalid values out of the database is easier than attempting to fix the data later. Fixing the data is often called data cleaning. Foreign keys were an easy way to make sure references were valid. Constraints can do the same thing for individual field values.

CheckConstraint

For the sake of discussion, suppose we want to prevent authors who were born in the future. So the birth_year field of the BirthYear class should be constrained to be less than or equal to 2020. This constraint is added as an additional argument in the column definition. We need to pass in a CheckConstraint object to the column definition.

As with the foreign key, inserting an invalid record will raise an integrity error, which will be caught and handled, as seen below.

Note: CheckConstraint must be imported from sqlalchemy. We’ve highlighted the new lines in the widget below.

Get hands-on with 1400+ tech skills courses.