What is CHECK Constraint in SQL Server?
Introduction:
In this article i will explain what is CHECK Constraint in SQL Server.
Description:
In previous articles i explained what is Constraint, how many Constraints available in SQL Server, and what is NOT NULL Constraint in SQL Server. Now i will explain what is CHECK Constraint in SQL Server.
CHECK Constraint:
CHECK constraint is used to check some kind of conditions on columns.
Example:
Create table Employee
(
EmpNo int,
EmpSalary decimal check(EmpSalary >= 5000)
)
Now Employee table is created with check constraint. In the above example you will see check(EmpSalary >= 0), means Employee table will accept the input data where salary is greater than or equivalent to 5000 only. Now insert some data into Employee table.
Insert into Employee values(1, 5000)
Successfully data inserted into Employee table.
Insert into Employee values(2, 6000)
Successfully data inserted into Employee table.
Insert into Employee values(3, 1000)
Now we got the following error:
The INSERT statement conflicted with the CHECK constraint "CK__Employee__EmpSal__1CF15040". The conflict occurred in database "Test", table "dbo.Employee", column 'EmpSalary'.
Because Employee table will accept data where EmpSalary >= 5000. First two statements satisfies the condition, i.e., data inserted into Employee table. In last statement EmpSalary < 5000. So, we got the above error.
-
CreatedOct 22, 2013
-
UpdatedOct 03, 2020
-
Views1,940