Welcome back! So far, we've covered constraints that enforce uniqueness and ensure data quality. Now let's explore CHECK constraints—your custom data validation enforcers.
CHECK constraints validate data against specific conditions before allowing it into your table.
Engagement Message
Think of a rule like "Age must be between 0 and 120." How would you enforce this without constraints?
CHECK constraints use logical expressions to test data validity. If the expression evaluates to TRUE, the data is accepted. If FALSE, it's rejected.
The syntax is simple: CHECK (logical_expression)
Engagement Message
What would happen if someone tried to enter an age of -5 with a CHECK constraint requiring age >= 0?
Here's how to add a CHECK constraint for numeric ranges:
Now only valid ages and positive salaries are allowed.
Engagement Message
What age values would this constraint reject?
Date ranges work similarly. You can ensure dates fall within reasonable windows:
This prevents events scheduled before 2024.
Engagement Message
Why might you want to restrict dates to future values only?
CHECK constraints excel at validating limited text lists. Perfect for status fields, categories, or types:
