Notes on Different Constraints in MySQL
Meaning of Constraints:
Constraints are rules applied to table columns in a database. They restrict the type of data that can
be inserted into a table. Constraints ensure accuracy, reliability, and consistency of the data.
Types of Constraints in MySQL
1. NOT NULL Constraint: Ensures that a column cannot have NULL values.
Example: CREATE TABLE Student (RollNo INT NOT NULL, Name VARCHAR(50) NOT NULL);
2. UNIQUE Constraint: Ensures all values in a column are different. Allows one NULL value.
Example: CREATE TABLE Employee (EmpID INT UNIQUE, Email VARCHAR(100) UNIQUE);
3. PRIMARY KEY Constraint: Combines NOT NULL and UNIQUE. Each row must have a unique,
non-null value.
Example: CREATE TABLE Customer (CustID INT PRIMARY KEY, Name VARCHAR(50));
4. FOREIGN KEY Constraint: Establishes a relationship between two tables. Refers to primary key
of another table.
Example: CREATE TABLE Orders (OrderID INT PRIMARY KEY, CustID INT, FOREIGN KEY
(CustID) REFERENCES Customer(CustID));
5. CHECK Constraint: Ensures values in a column satisfy a specific condition.
Example: CREATE TABLE Product (ProductID INT PRIMARY KEY, Price DECIMAL(8,2) CHECK
(Price > 0), Quantity INT CHECK (Quantity >= 1));
6. DEFAULT Constraint: Provides a default value if no value is specified.
Example: CREATE TABLE Accounts (AccID INT PRIMARY KEY, Balance DECIMAL(10,2)
DEFAULT 1000.00);
7. AUTO_INCREMENT Constraint: Automatically generates a unique number for each row.
Usually with PRIMARY KEY.
Example: CREATE TABLE Users (UserID INT AUTO_INCREMENT PRIMARY KEY, Username
VARCHAR(50) NOT NULL);
Constraint Description
NOT NULL Column cannot store NULL values.
UNIQUE All values must be unique.
PRIMARY KEY Unique + Not Null, identifies each row.
FOREIGN KEY Refers to primary key of another table.
CHECK Ensures condition on values.
DEFAULT Provides default value if not given.
AUTO_INCREMENT Automatically generates sequential values.