Foreign Keys and Relationships
# CHAPTER 13
Foreign Keys and Relationships
1. Introduction
A database without relationships is just a glorified Excel spreadsheet. The true power of a Relational Database Management System (RDBMS) lies in its ability to connect independent tables together. If a user writes a blog post, how does the database know who wrote it without copying the user's name into the post? It uses a Foreign Key. In this chapter, we will learn how to architect and mathematically enforce the three core types of database relationships.2. Learning Objectives
By the end of this chapter, you will be able to:- Define a Foreign Key constraint.
- Architect One-to-One (1:1) relationships.
- Architect One-to-Many (1:N) relationships.
- Architect Many-to-Many (N:M) relationships using Pivot tables.
-
Enforce Referential Integrity using
ON DELETE CASCADE.
3. What is a Foreign Key?
A Foreign Key (FK) is a column in one table that refers to the Primary Key (PK) of another table. The Foreign Key acts as the mathematical bridge between the two tables.*Crucially*, applying a Foreign Key constraint tells MySQL: *"Do not allow a number in this column unless that exact ID number actually exists in the other table."* This prevents "Orphaned Records" (e.g., an order belonging to user ID 999, when user 999 doesn't exist!).
4. The One-to-Many Relationship (1:N)
This is the most common relationship in web development.- One User can have Many Orders.
- One Department can have Many Employees.
The Rule: The Foreign Key always goes on the "Many" side.
5. The Many-to-Many Relationship (N:M)
- Many Students can enroll in Many Classes.
- Many Classes can hold Many Students.
You cannot put a Foreign Key in the students table, nor the classes table, because you would need multiple IDs in a single cell (which violates Normalization).
The Solution: You must create a 3rd table in the middle, called a Pivot Table (or Junction Table). It holds nothing but Foreign Keys!
6. The One-to-One Relationship (1:1)
- One User has One Social Security Profile.
UNIQUE constraint to it so it cannot be used twice!
7. Referential Integrity: ON DELETE CASCADE
What happens if you delete a User, but they have 5 Orders pointing to their ID?
By default, MySQL will block the deletion and throw an error to protect data integrity.
If you *want* MySQL to automatically delete all the user's orders when the user is deleted, you append ON DELETE CASCADE to the Foreign Key definition.
8. Common Mistakes
-
Data Type Mismatches: If the Primary Key
idin theuserstable is anINT, the Foreign Keyuser_idin theorderstable MUST also be anINT. If one is aBIGINTand the other is anINT, the constraint will fail to create.
-
Putting the FK on the wrong side: In a 1:N relationship (One Department has Many Employees), beginners often try to put an
employees_listcolumn inside thedepartmentstable. This violates 1NF. Thedepartment_idFK must go inside theemployeestable!
9. Best Practices
-
Foreign Key Naming Convention: Always name your Foreign Key columns as the singular name of the parent table, followed by
_id. (e.g., Parent tableusers-> Foreign Keyuser_id). This makes writing JOIN queries infinitely easier to read.
10. Exercises
- 1. In a blog application where one User can write many Comments, in which table should the Foreign Key be placed, and what should it be named?
-
2.
Why is a "Pivot Table" strictly required to map a Many-to-Many relationship between
productsandcategories?
11. MCQ Quiz with Answers
What is the primary purpose of adding a FOREIGN KEY constraint to a column, rather than just using a standard INT column to hold the ID?
What will happen if you attempt to DELETE a row from a parent table (like users) while a child table (like orders) still contains rows pointing to that user's ID, assuming you did NOT use ON DELETE CASCADE?
12. Interview Questions
- Q: Describe the architectural structure required to implement a Many-to-Many relationship in a relational database. Why can't it be done with just two tables?
- Q: Explain what "Referential Integrity" means in the context of database architecture and how Foreign Keys enforce it.
13. FAQs
Q: Can a table have multiple Foreign Keys? A: Yes! A table likeorder_details will usually have a product_id (pointing to the products table) AND an order_id (pointing to the orders table).