The foundation of relational database design — primary keys identify rows uniquely, foreign keys create relationships between tables, and together they enforce data integrity.
Scenario: You're organizing a school database. How do you ensure:
Think about it: What system would you use to identify and connect students?
Real-world parallel: Your Social Security Number, Passport Number, or Student ID
Definition: A column (or set of columns) that uniquely identifies each row in a table.
Rules for Primary Keys:
Example: STUDENTS table
-- Sample data:

Why is student_id the primary key?
Bad primary key choices:
Real-world parallel: A reference number on a package pointing to your address
Definition: A column that references the primary key of another table, creating a relationship.
Example: ENROLLMENTS table
Visual relationship:

Alice (student_id: 1001) is enrolled in: → CS101 (via enrollment_id 1) → MATH200 (via enrollment_id 2)
CS101 has these students: → Alice (student_id: 1001) → Bob (student_id: 1002)
Match the key type to its role:
| Scenario | Primary Key or Foreign Key? |
|---|---|
| Social Security Number in PEOPLE table | ? |
| Customer ID in ORDERS table referencing CUSTOMERS | ? |
| Order ID in ORDERS table | ? |
| Product ID in ORDER_ITEMS table referencing PRODUCTS | ? |
Think about each one...
Answers:
What Foreign Keys Prevent:
Scenario 1: Orphaned Records
Try to insert enrollment for non-existent student
-- Student 9999 doesn't exist!-- Result: ❌ ERROR: Foreign key constraint violated!-- Database says: "Can't enroll a student that doesn't exist!
Scenario 2: Broken References -- Try to delete a student who has enrollments
-- Result: ❌ ERROR: Foreign key constraint violated
-- Database says: "Can't delete student with existing enrollments!"
-- (You'd have orphaned enrollments pointing to non-existent student)Options for handling deletions:
-- CASCADE: Delete enrollments when student is deleted
FOREIGN KEY (student_id) REFERENCES students(student_id) ON DELETE CASCADE SET NULL: Set student_id to NULL in enrollments FOREIGN KEY (student_id) REFERENCES students(student_id) ON DELETE SET NULL; -- RESTRICT: Prevent deletion (default) FOREIGN KEY (student_id) REFERENCES students(student_id) ON DELETE RESTRICT;
Mental model: Foreign keys are like safety ropes in mountain climbing. They ensure you can't fall off a cliff (create invalid references) and keep everything connected safely!
CUSTOMERS table
ORDERS table
ORDER_ITEMS table
PRODUCTS table
The relationships:

| Aspect | Primary Key | Foreign Key |
|---|---|---|
| Purpose | Uniquely identify rows | Link to other tables |
| Uniqueness | Must be unique | Can have duplicates |
| Null Values | Cannot be NULL | Can be NULL (optional relationship) |
| Quantity | One per table | Multiple per table |
| Auto-Indexed | Yes, always | Should be indexed |
| Example | Student ID | Student ID in Enrollments table |
Mental model: