Check Constraint in MS SQL Server

Check Constraint :
It is used alongside relational operators to check whether a value satisfies the condition or not (boolean). If the condition is satisfied, the boolean expression sets to True otherwise False. The check constraint does not have a specific syntax. It is used along with the create table syntax.

Syntax :

Create table Marks 
name varchar2(30), 
rollnumber number primary key, 
marks int check (marks<=75)

A table named Student is created along with the condition that marks must not be greater than 75. A user inserts a few values as shown below –

Table – Marks

Name Rollnumber Marks
Aisha 111 60
Naina 112 73

The values are inserted as per the conditions mentioned in the create table syntax. The user tries inserting a few more values yet errors occur as shown below –



Example-1:

Insert into Student 
values('Maya', '117', '80')

Output –
The value results in an error as the value is greater than 75.


Example-2:

Insert into Student 
values('Maya' '111', '74')

Output –
An error is displayed. This is due to the primary key used for rollnumber. Primary key forbids the use of duplicates in a table.


Check constraint in case of NULL :

Insert into Student 
values('Riya', '112', 'NULL')

Output –
In SQL, NULL is used incase of unknown value. Therefore it is considered as False.

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.