SQL Constraints Explained

In this blog, I will explain the SQL Constraints.

Introduction
 
In this blog, I will explain SQL Constraints. They are used to specify rules for the data in a table. The following SQL Constraints are commonly used (Primary key, foreign key, unique key, Composite key, null, Not Null, check).
 
 
 
Primary Key
 
The Primary key must contain be a unique value. It is the primary column and can’t have the null value. It uniquely identifies each row in a database table.
 
Syntax
  1. CREATE TABLE TB_NAME(Column1 datatype,column2 datatype PRIMARY KEY(Column1))  
Foreign Key
 
1. Foreign key always refers to the primary key column.
2. Foreign key accepted to duplicate value.
 
Syntax
  1. CREATE TABLE TB_NAME(column1 datatype FOREIGN KEY REFERENCES(primary_key column_name),cloumn2 datatype)  
Unique Key
 
The unique key is the same as the primary key, but one row is accepted for the null value.
 
Syntax
  1. CREATE TABLE TB_NAME(Column_name datatatype UNIQUE,column_name2 datatype)  
Composite key
 
A composite key is a set of multiple keys that, together, uniquely identifies each record
 
Syntax
  1. CREATE TABLE TB_NAME(Column1 datatype,column2 datatype PRIMARY KEY(Column1,column2))  
Not Null
 
Forces a column not to accept NULL values
 
Syntax
  1. CREATE TABLE TB_NAME(Column1 datatype,column2 datatype NOT NULL)  
Check
 
The CHECK constraint is used to limit the value range that can be placed in a column.
 
Syntax
  1. CREATE TABLE TB_NAME(MARKS INT CHECK(MARKS<=100))