CHECK Constraint
All the records in a particular column must adhere to a specified criterion, and this is where the CHECK constraint comes in. This constraint is typically used to enforce business logic on values in a column, preventing the entry of inaccurate data. The CHECK constraint may be specified either when the table is created or may be added later using an ALTER statement. Imagine we add a column in our Costumer table which holds information about the customers’ age. Moreover, we’d like to make sure that all customers are over 18 years old. Then, we’d write the following query:
TEXT/X-SQL
1CREATE TABLE Customer (
2 Customer_Id int NOT NULL UNIQUE,
3 Age int,
4 CHECK (Age>18)
5);
To create a CHECK constraint on the Age column after the table has been created, we use the following syntax:
TEXT/X-SQL
1ALTER TABLE Customer (
2ADD CHECK (Age>18)
3);