You are currently viewing How To Add Check Constraint on SQL Server Table

How To Add Check Constraint on SQL Server Table

CHECK constraint on a column enables a condition to check the value being entered into a record. If the condition evaluates to true the record will be inserted and if the condition evaluates to false the record violates the constraint and isn’t entered the table.

For example, in an employee table you have an age column and there is a check constraint that only 18+ age employees should be inserted. Then if you try to enter age of employee less than 18 it violates the condition and does not allow entering record.

CHECK Constraint on CREATE TABLE

In the following example, We have CHECK Constraint on EmpAge column, where EmpAge can not be inserted less than 18 years.

CHECK Constraint on ALTER TABLE

ALTER TABLE tblEmployee
ADD CHECK (EmpAge>=18)

We can add CHECK Constraint name on ALTER TABLE.

ALTER TABLE tblEmployee
ADD CONSTRAINT CHK_tblEmployee_Age CHECK (EmpAge>=18 )

Let’s try to insert EmpAge less than 18 years in the table.

By inserting EmpAge less than 18 years, we get an error of CHECK Constraint, as shown in the above image.

Recommended Readings