Constraints in MySQL are rules that govern what type of data can be inserted into a particular column of a table. In simple words, constraints are rules used to enforce limitations on the data inserted into a table.
For example, a customer name should not be empty, or a student ID should not be duplicated. You can enforce this condition using constraints.
Constraints are one of the most important features of MySQL because they prevent the insertion of invalid data into a table. They help maintain the accuracy, integrity, consistency, and reliability of data in the database table. If any constraint is violated during a data operation, the operation is aborted and MySQL generates an error.
Syntax to Apply Constraints in MySQL
The general syntax to apply constraints in MySQL when using CREATE TABLE statement is:
CREATE TABLE table_name (
column1 datatype(size) constraint,
column2 datatype(size) constraint,
column3 datatype(size) constraint
);Example:
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE
);Types of Constraints in MySQL
MySQL provides several types of constraints to enforce data integrity and accuracy in tables.
| Constraint | Description |
|---|---|
| NOT NULL | Prevents NULL values. |
| UNIQUE | Prevents duplicate values. |
| PRIMARY KEY | Uniquely identifies each row in a table. |
| FOREIGN KEY | Creates relationship between data into two tables. |
| CHECK | Restricts values based on conditions. |
| DEFAULT | Assigns default values for columns if not specified. |
| AUTO_INCREMENT | Automatically generates numbers. |
Advantages of Constraints
There are the following advantages of constraints in MySQL:
- Constraints maintain data integrity so that only valid and consistent data is stored in the database.
- PRIMARY KEY and UNIQUE constraints prevent duplicate values from being inserted into a table.
- Constraints improve data accuracy by preventing the insertion of invalid data.
- Constraints help reduce accidental data corruption and maintain database consistency.
- The database automatically validates data according to the defined rules and conditions.
- A FOREIGN KEY constraint ensures that related records exist in the parent table, thereby maintaining referential integrity.
- Constraints help reduce accidental data corruption and maintain database consistency.





