Day 60 – SQL CHECK Keyword
SQL CHECK keyword is used to define a condition that must be satisfied by the values in a column when new data is inserted or updated in a table. It is also known as a check constraint.
The syntax for using the CHECK keyword is as follows:
CREATE TABLE table_name ( column1 datatype constraint_name CHECK (condition), column2 datatype, ... );
column1 is the name of the column that you want to add the constraint to,
datatype is the data type of the column,
constraint_name is an optional name for the constraint, and
condition is the condition that must be satisfied by the values in the column.
For example, the following SQL statement creates a table named “Students” with a check constraint on the “Age” column to ensure that the age of the students is between 18 and 30:
CREATE TABLE Students ( StudentID INT PRIMARY KEY, Name VARCHAR(50), Age INT CHECK (Age BETWEEN 18 AND 30), Gender VARCHAR(10) );
In this case, the
CHECK keyword is used to define a condition that must be satisfied by the values in the Age column, and any attempts to insert or update data in the table that violates this condition will result in an error.
Note that the
CHECK keyword can be used with various logical operators, such as
LIKE, and more, to define complex conditions for the values in a column.
CHECK constraint is a powerful tool for ensuring data integrity and consistency in a database, and it can be used to enforce various business rules and policies on the data.