Skip to content

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.

  1. 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.
  2. 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ΒΆ

CREATE TABLE students (
    student_id INT PRIMARY KEY, -- βš“ The Anchor
    name VARCHAR(50)
);

πŸ’» 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)
);

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:

  1. ON DELETE CASCADE: If you delete a Customer, delete all their Orders too. πŸŒͺ️
  2. ON DELETE SET NULL: If you delete a Customer, keep the Orders but set their customer_id to blank. βšͺ
  3. 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

πŸ“ˆ Learning PathΒΆ