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.
💻 Live Code Editor
Is page ki language (MYSQL) mein code likhein aur turant chalाएं — yahीं, bina kuch install kiye.Powered by OneCompiler. Agar editor na khule to yahान naye tab mein kholein.
💻 Live Code Editor
Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें.
Agar load na ho to naye tab mein kholें.