Understanding Constraints in
MySQL
Ensuring Data Integrity and Consistency in Relational
Databases
Presented by: Your Name
Date
What Are Constraints?
• Constraints are rules enforced on data in a table to ensure accuracy,
consistency, and integrity.
• Why Use Constraints?
• - Prevent invalid data
• - Enforce relationships
• - Ensure business rules
Types of Constraints in MySQL
• PRIMARY KEY - Uniquely identifies each row
• FOREIGN KEY - Enforces referential integrity
• UNIQUE - Ensures column values are unique
• NOT NULL - Disallows NULL values
• DEFAULT - Sets default value if none provided
• CHECK (8.0.16+) - Validates data with conditions
PRIMARY KEY Constraint
• • Uniquely identifies each record
• • Cannot contain NULLs
• • Only one primary key per table
• Example:
• CREATE TABLE Students (
• ID INT PRIMARY KEY,
• Name VARCHAR(50)
• );
FOREIGN KEY Constraint
• • Links two tables together
• • Enforces integrity between parent-child records
• Example:
• FOREIGN KEY (DeptID)
• REFERENCES Departments(DeptID)
• ON DELETE CASCADE
NOT NULL Constraint
• • Prevents NULL (empty) values
• • Ensures required data is entered
• Example:
• Name VARCHAR(50) NOT NULL
UNIQUE Constraint
• • Ensures all values in a column are different
• • Allows NULL (unless combined with NOT NULL)
• Example:
• Email VARCHAR(100) UNIQUE
DEFAULT Constraint
• • Provides default value if none is given
• Example:
• Status VARCHAR(20) DEFAULT 'Pending'
CHECK Constraint
• • Ensures values meet a condition
• • Supported from MySQL 8.0.16+
• Example:
• CHECK (Age >= 18)
Modifying Constraints
• Add Constraint:
• ALTER TABLE Students ADD CONSTRAINT chk_age CHECK (Age >= 18);
• Drop Constraint:
• ALTER TABLE Students DROP CHECK chk_age;
• ALTER TABLE Employees DROP FOREIGN KEY fk_dept;
Viewing Constraints
• Query to List Constraints:
• SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
• WHERE TABLE_NAME = 'YourTable';
• Use this to inspect existing constraints on a table.
Best Practices
• • Always name your constraints
• • Use constraints to enforce rules at the database level
• • Combine NOT NULL, UNIQUE, and DEFAULT effectively
• • Use FOREIGN KEY with ON DELETE/UPDATE actions thoughtfully
Summary
• • Constraints are essential for data integrity
• • MySQL supports several types for different use cases
• • Learn to define, modify, and drop constraints efficiently
Questions & Answers
• Open the floor for questions and discussion.