What is CHECK key constraint in SQL Server ?

By using CHECK key constraint we can add condition to filter data before inserting in columns.
While inserting data if we violate the condition then server will give an error.


1) Add CHECK key constraint on table by Query.
In below example we are creating new table of tblStudentDetails and we will apply check that student age should not be greater than 30.

Example

CREATE TABLE tblStudentDetails
(
Id INT IDENTITY (1,1),
StudentName VARCHAR (50),
City VARCHAR (50),
Age INT CHECK (Age <= 30)
)

2) Add CHECK key constraint on table using table design.

Step 1 :


add check key constraint in sql server

Step 2 :


add check key constraint in sql server

Step 3 : Save table.


Table already having three rows and Age values are less or equal to 30. Consider below result set of tblStudentDetails table.

check key constraint in sql server

Let's try to insert new student details who having Age more than 30.

Example

INSERT INTO tblStudentDetails (StudentName, City, Age)
VALUES ('Rahul', 'Pune', 35)

Output

The INSERT statement conflicted with the CHECK constraint


Note : In above example we CHECK key constraint on student Age column which accept only value less than or equal to 30. So in above query we are trying to insert Age value more than 30 so it gives an error.


To remove the error insert correct data in table.

Example

INSERT INTO tblStudentDetails (StudentName, City, Age)
VALUES ('Rahul', 'Pune', 30)

Output

check key constraint in sql server


List student table details to see inserted data.

check constraint in sql server