Primary & Foreign Keys ποΈΒΆ
Prerequisites: CREATE TABLE, NOT NULL & UNIQUE
Mentor's Note: Primary Keys and Foreign Keys are the DNA of a Relational Database. They define who everyone is and how they are related. Master this, and you can build any complex system! π‘
π The Scenario: The School System π«ΒΆ
Imagine a school with Students and Classes.
- Primary Key (The ID Card π): Every student has a Roll Number. No two students share one, and no student is without one. It is their unique anchor.
- Foreign Key (The Enrollment π): In the 'Grades' table, we list the Roll Number. This links the grade back to the specific student in the main registry.
π» 1. Primary Key (The Anchor β)ΒΆ
A Primary Key is a combination of NOT NULL and UNIQUE. It uniquely identifies each record.
SyntaxΒΆ
π» 2. Foreign Key (The Bridge π)ΒΆ
A Foreign Key links a column in one table (Child) to the Primary Key of another table (Parent). This ensures Referential Integrity.
SyntaxΒΆ
CREATE TABLE orders (
order_id INT PRIMARY KEY,
order_date DATE,
customer_id INT,
-- π Building the bridge to the Customers table
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
π¨ Visual Logic: The LinkΒΆ
erDiagram
CUSTOMER ||--o{ ORDER : "places"
CUSTOMER {
int id PK
string name
}
ORDER {
int order_id PK
date order_date
int customer_id FK
}
π‘οΈ Referential Integrity ActionsΒΆ
What happens if you delete a Parent row? SQL lets you choose:
- ON DELETE CASCADE: If you delete a Customer, delete all their Orders too. πͺοΈ
- ON DELETE SET NULL: If you delete a Customer, keep the Orders but set their
customer_idto blank. βͺ - NO ACTION (Default): Prevent the deletion of the Customer if they still have Orders. π«
-- Example: Auto-delete orders when customer is removed
FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
π Comparison TableΒΆ
| Feature | Primary Key | Foreign Key |
|---|---|---|
| Purpose | Uniquely identify a row π€ | Link to another table π |
| Duplicates? | β No | β Yes |
| NULLs? | β No | β Yes (Usually) |
| Limit | Only 1 per table | Multiple per table |