Open In App

Check Constraint in MS SQL Server

Last Updated : 26 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads