MySQL Constraints

MySQL Constraints
In MySQL, constraints are rules applied to columns or tables to enforce data integrity and ensure the accuracy and reliability of data.
Types of MySQL Constraints
| Constraint | Description |
|---|---|
| PRIMARY KEY | Uniquely identifies each row in a table. A table can have only one primary key, but it can consist of multiple columns (composite key). |
| FOREIGN KEY | Enforces a link between columns in two tables to maintain referential integrity. |
| UNIQUE | Ensures that all values in a column are distinct. |
| NOT NULL | Ensures that a column cannot have NULL values. |
| DEFAULT | Sets a default value for a column if no value is specified. |
| CHECK | Ensures that values meet a specific condition. (Available in MySQL 8.0+) |
Examples
PRIMARY KEY
iduniquely identifies each student.
FOREIGN KEY
Ensures that
Students.dept_idmust exist inDepartments.dept_id.
UNIQUE
Prevents duplicate emails in the
Userstable.
NOT NULL
namecolumn cannot be NULL.
DEFAULT
If
marksis not specified, it defaults to0.
CHECK
Ensures
marksare between 0 and 100.
Key Points
Constraints enforce data integrity and validity.
Can be applied at the column level or table level.
Primary key + foreign key establish relationships between tables.
UNIQUE, NOT NULL, DEFAULT, CHECK help control valid input.
Constraints can be added or removed using
ALTER TABLE.
