Get Started: SQL CHECK Constraint

In This Article, You Will Know About SQL CHECK Constraint.

Before moving ahead, let’s know a bit about the SQL UNIQUE Constraint.

Table of Contents

SQL CHECK Constraint

The SQL CHECK Constraint applies a rule or set of rules that check the values based on certain conditions.

Table1: Student_Info

Serial Number

Name

Class

Roll_No

Subject

1

A

I

111

Eco

2

B

II

121

Math

3

C

III

131

Sci

4

D

IV

141

Eng

MySQL Server

Example: Use the CHECK Constraint to return the data based on a rule.

				
					CREATE TABLE Student_Info (
	Serial Number int NOT NULL,
	Name char(10),
	Class char(5),
	Roll_No int,
	CHECK (Roll_No = 121)
);

				
			

SQL Server

Example: Use the CHECK Constraint to return the data based on a rule.

				
					CREATE TABLE Student_Info (
	Serial Number int NOT NULL,
	Name char(10),
	Class char(5),
	Roll_No int CHECK (Roll_No = 121)
);
				
			

Apply CHECK on multiple columns after the table is created.

MySQL / SQL Server 

Example: Use the CHECK Constraint to return the data based on a rule.

				
					CREATE TABLE Student_Info (
	Serial Number int NOT NULL,
	Name char(10),
	Class char(5),
	Roll_No int, 
    CONSTRAINT Table_Constraint CHECK (Serial Number < 4 AND Roll_No >= 121)
);
				
			

SQL CHECK on ALTER TABLE

Apply CHECK after the table is created.

MySQL / SQL Server

Example: Use the CHECK Constraint to return the data based on a rule.

				
					ALTER TABLE Student_Info
ADD CHECK (Name = 'C');
				
			

Apply CHECK on multiple columns after the table is created.

MySQL / SQL Server 

Example: Use the CHECK Constraint to return the data based on a rule.

				
					ALTER TABLE Student_Info
ADD CONSTRAINT Table_Constraint CHECK (Serial Number < 4 AND Roll_No >= 121);
				
			

DROP CHECK Constraint

SQL Server

Example: Use the CHECK Constraint to return the data based on a rule.

				
					ALTER TABLE Student_Info
DROP CONSTRAINT Table_Constraint;
				
			

MySQL

Example: Use the CHECK Constraint to return the data based on a rule.

				
					ALTER TABLE Student_Info
DROP CHECK Table_Constraint;
				
			

If you find anything incorrect in the above-discussed topic and have further questions, please comment below.

Connect on:

1 thought on “Get Started: SQL CHECK Constraint”

Leave a Comment

Stay in the loop

codingstreets