SQL Constraints: The Data Rules βοΈΒΆ
Prerequisites: Create Table Basics
Mentor's Note: Constraints are the "Guardrails" of your database. Without them, you could have a student with no name, or a negative salary. Constraints ensure your data stays high-quality and trustworthy. π‘
π The Scenario: The School Registry π«ΒΆ
Imagine you are the principal of a school.
- NOT NULL: Every student must have a name. π€
- UNIQUE: No two students can have the same Email ID. π§
- PRIMARY KEY: Every student must have a unique Roll Number to identify them. π
- CHECK: A student's age must be at least 5 years old. π
- DEFAULT: If no city is provided, assume they are from "Surat". π
π¨ Visual Logic: The Constraint GuardΒΆ
graph TD
A[Data Entry π₯] --> B{Constraints?}
B -- "Fail β" --> C[Reject Action π«]
B -- "Pass β
" --> D[Save to Table ποΈ]
subgraph "Rule Set"
B1[NOT NULL]
B2[UNIQUE]
B3[PRIMARY KEY]
B4[CHECK]
end
π» Common Constraints (DDL Syntax)ΒΆ
π Deep Dive: Primary vs Foreign KeyΒΆ
1. Primary Key (The Anchor β)ΒΆ
- Unique identify for every row.
- Cannot be NULL.
- Only one per table.
2. Foreign Key (The Bridge π)ΒΆ
- Links one table to another.
- Points to the Primary Key of another table.
- Maintains Referential Integrity.
-- π Linking Employees to Departments
CREATE TABLE EMPLOYEE (
emp_id NUMBER PRIMARY KEY,
dept_id NUMBER REFERENCES DEPARTMENT(dept_id) -- π Foreign Key
);
π Comparison TableΒΆ
| Constraint | Can be NULL? | Unique? | Limit per Table |
|---|---|---|---|
| PRIMARY KEY | β No | β Yes | Only 1 |
| UNIQUE | β Yes | β Yes | Multiple |
| NOT NULL | β No | β No | Multiple |
π‘ Interview Tip πΒΆ
"Interviewers often ask: 'Can a UNIQUE constraint have a NULL value?' The answer is YES! In most databases, you can have one (or sometimes multiple) NULL values in a UNIQUE column, because NULL is not equal to NULL."
π Learning PathΒΆ
π‘ Pro Tip: "Bad data is worse than no data. Use constraints early so you don't have to clean up a mess later."