SQL Constraints Explained
SQL constraints are rules applied to columns or tables to enforce data integrity and data quality.
Types of SQL Constraints
- PRIMARY KEY
- FOREIGN KEY
- UNIQUE
- NOT NULL
- CHEK
- DEFAULT
PRIMARY KEY :-
A PRIMARY KEY is uniquely identifies each record in a table.
CREATE TABLE employee(
employeeID INT PRIMARY KEY,
employeeName VARCHAR(100),
salary DECIMAL(10,2)
);Trying to insert another employee with employeeID =101 will violate the primary key constraint.
FOREIGN KEY :-
A FOREIGN KEY create a relationship between two tables.
CREATE TABLE departments(
departmentID INT PRIMARY KEY,
departmentName VARCHAR(100)
);
NOW CREATE AN EMPLOYEE TABLE
CREATE TABLE employees(
employeeId INT PRIMARY KEY,
employeeName VARCHAR(100),
departmentID INT,
FOREIGN KEY(departmentID)
REFERENCES departments(departmentID)
);The departmentID in employees references departmentID in departments.
Get Sanjay Singh’s stories in your inbox
Join Medium for free to get updates from this writer.
UNIQUE :-
The UNIQUE constraint ensures that values in a column are not duplicated.
CREATE TABLE employee(
employeeID INT PRIMARY KEY,
employeeName VARCHAR(100),
email VARCHAR(50) UNIQUE
);Two employee cannot have the same email id.
NOT NULL :-
The NOT NULL constraint prevents a column from containing NULL.
CREATE TABLE employee(
employeeID INT PRIMARY KEY,
employeeName VARCHAR(100) NOT NULL
);This means employeeName must have a value.
CHECK :-
The CHECK constraint ensure that data satisfies a specified condition.
CREATE TABLE employee(
employeeID INT PRIMARY KEY,
employeeName VARCHAR(100),
salary DECIMAL(10,2)
CHECK(salary > 0)
);Now this would violate the constraint.
DEFAULT :-
The DEFAULT constraint provides a default value when the user doesn’t provide one.
CREATE TABLE employee(
employeeID INT PRIMARY KEY,
employeeName VARCHAR(100),
country VARCHAR(100) DEFAULT 'India'
);





