Constraints
Explore how to maintain database integrity by using constraints with SQLAlchemy. Understand how to implement field-level checks, uniqueness constraints, and multi-column conditions to prevent invalid data. Learn the advantages and limitations of constraints to keep your database accurate and reliable.
We'll cover the following...
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 ...