MySQL + SQL · Lesson 38
Constraints in MySQL
What are Constraints?
Constraints are rules applied to columns to keep data correct and valid. They are enforced automatically by MySQL.
Main Constraints
| Constraint | Meaning |
|---|---|
| NOT NULL | Column cannot be empty |
| UNIQUE | No duplicate values |
| PRIMARY KEY | Unique + not null |
| FOREIGN KEY | Links to another table |
| CHECK | Value must satisfy a condition |
| DEFAULT | Auto value if none given |
Example
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(60) UNIQUE,
marks INT CHECK (marks BETWEEN 0 AND 100),
status VARCHAR(10) DEFAULT 'active'
);
Summary
- Constraints: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT.
- They keep stored data valid automatically.