MySQL Table Design Data Integrity
In MySQL, constraints are rules applied to columns or tables to control what type of data can be stored. They help maintain accuracy, consistency, and reliability of data in your database.
Common constraints include:
NULL values. The user must always provide a value.NOT NULL and UNIQUE. Each table should normally have one primary key.You can add constraints in two ways:
Example ideas:
ID the PRIMARY KEY.Name NOT NULL so it must always be provided.Email UNIQUE so no duplicate email is allowed.DepartmentID to link to a Departments table.
-- Create Employees table with common constraints
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Age INT,
Email VARCHAR(100) UNIQUE,
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Departments(ID)
);
-- Add a foreign key to an existing table
ALTER TABLE Employees
ADD CONSTRAINT fk_employees_department
FOREIGN KEY (DepartmentID)
REFERENCES Departments(ID);
Employees without a Name, MySQL will throw an error because of the NOT NULL constraint.Email, the UNIQUE constraint will prevent it.PRIMARY KEY on ID ensures each employee has a unique identifier.FOREIGN KEY on DepartmentID ensures that any department assigned to an employee must already exist in the Departments table.Email, Username, or Phone to avoid duplicates.ALTER TABLE.Students with constraints:
StudentID – INT, PRIMARY KEYName – VARCHAR(100), NOT NULLEmail – VARCHAR(100), UNIQUECourses and link it with Students using a FOREIGN KEY.ALTER TABLE to add a new UNIQUE constraint to an existing column in any table.