=SQL Constraints
SQL constraints are rules used to limit or control the type of data that can go into a table.
They ensure data accuracy, consistency, and integrity.
1. PRIMARY KEY
Definition: Uniquely identifies each record in a table. It cannot be NULL and must be unique.
Example:
CREATE TABLE Employee (
Emp_Id INT PRIMARY KEY,
Emp_Name VARCHAR(50)
);
Note: Only one primary key per table. Automatically creates a unique index.
2. FOREIGN KEY
Definition: Links two tables together. It refers to the Primary Key in another table.
Example:
CREATE TABLE Department (
Emp_Id INT,
Dept_Name VARCHAR(50),
FOREIGN KEY (Emp_Id) REFERENCES Employee(Emp_Id)
);
Note: Maintains referential integrity between tables (no orphan records).
3. UNIQUE
Definition: Ensures that all values in a column are different (but it can contain NULL once).
Example:
CREATE TABLE Employee (
Email VARCHAR(50) UNIQUE,
Mobile_No VARCHAR(15) UNIQUE
);
Note: Used to define Alternate Keys or Candidate Keys other than the primary key.
4. NOT NULL
Definition: Ensures that a column cannot have NULL values (it must always contain data).
Example:
CREATE TABLE Employee (
Emp_Name VARCHAR(50) NOT NULL
);
Note: Often used with primary or unique keys to ensure valid entries.
5. CHECK
Definition: Used to validate a condition on column data before insertion or update.
Example:
CREATE TABLE Employee (
Emp_Id INT PRIMARY KEY,
Age INT CHECK (Age >= 18)
);
Note: Rejects any record where condition fails (e.g., Age < 18 won’t be allowed).
6. DEFAULT
Definition: Sets a default value for a column when no value is provided.
Example:
CREATE TABLE Employee (
Emp_Id INT PRIMARY KEY,
City VARCHAR(50) DEFAULT 'Not Specified'
);
Note: Useful for optional data fields (like default city, status, etc.).
7. AUTO_INCREMENT / IDENTITY
Definition: Automatically generates a unique number for each new record (used with
primary keys).
Example:
CREATE TABLE Employee (
Emp_Id INT PRIMARY KEY AUTO_INCREMENT,
Emp_Name VARCHAR(50)
);
Note: Automatically increments values — no need to manually enter Emp_Id.
8. INDEX (not exactly a constraint but often used together)
Definition: Used to speed up searches and queries on a table.
Example:
CREATE INDEX idx_emp_name
ON Employee (Emp_Name);
Note: Does not enforce rules, just improves query performance.
Summary Table
Constraint Purpose Allows NULL? Example
PRIMARY KEY Uniquely identifies No Emp_Id INT
each row PRIMARY KEY
FOREIGN KEY Links to another Yes FOREIGN KEY
table (Emp_Id)
UNIQUE Ensures all values Yes (one NULL Email UNIQUE
are unique allowed)
NOT NULL Value must not be No Emp_Name NOT
NULL NULL
CHECK Validates condition Yes CHECK (Age >= 18)
DEFAULT Provides a default Yes DEFAULT 'Not
value Specified'
AUTO_INCREMENT Generates auto No AUTO_INCREMENT
/ IDENTITY number
INDEX Speeds up search Yes CREATE INDEX ...
(not integrity)