In this tutorial, we will learn how to use CHECK CONSTRAINT
using SQL.
SQL CHECK
constraint ensures that all the values in a column satisfied the certain conditions.
Once CHECK
constraint is defined, a new record is inserted if specific values satisfy the CHECK
constraint condition. And updating an existing record if specific values satisfy the CHECK
constraint condition.
To add a CHECK
constraint when a new table is created, a statement is as follow:
CREATE TABLE Employee (
ID int NOT NULL,
EmpName varchar(255) NOT NULL,
City varchar(255),
Age int,
CONSTRAINT CHK_Person CHECK (Age>=18)
);
CREATE TABLE Employee (
ID int NOT NULL,
EmpName varchar(255) NOT NULL,
City varchar(255),
Age int CHECK (Age>=18)
);
CREATE TABLE Employee (
ID int NOT NULL,
EmpName varchar(255) NOT NULL,
City varchar(255),
Age int,
CHECK (Age>=18)
);
To add a CHECK
constraint after creating a table,
ALTER TABLE Employee
ADD CHECK (Age>=18);
ALTER TABLE Employee
ADD CONSTRAINT CHK_EmpAge CHECK (Age>=18);
To drop a CHECK
constraint, a statement is as follow:
ALTER TABLE Employee
DROP CONSTRAINT chk_constraintName;
ALTER TABLE Employee
DROP CONSTRAINT CHK_EmpAge;
ALTER TABLE Employee
DROP CHECK CHK_EmpAge;