That's a great question! Now that you know what a Primary Key is, understanding the Foreign Key is the next step in linking your data together.
A Foreign Key is a field (or collection of fields) in one table that refers to the Primary Key in another table. It acts as a "link" or a "bridge" between two tables.
How it works in your current lab:
You have two tables: categories and inventory_items.
- In the
categoriestable,category_idis the Primary Key. It uniquely identifies a category (like "Electronics" or "Furniture"). - In the
inventory_itemstable, you also have acategory_idcolumn. This is the Foreign Key.
CREATE TABLE inventory_items (
...
category_id INT, -- This is the Foreign Key column
...
FOREIGN KEY (category_id) REFERENCES categories(category_id)
);
Why do we use it?
- Relationship: It tells the database, "This item in the inventory belongs to that specific category."
- Data Integrity (Referential Integrity): It prevents mistakes. For example, you cannot add an item to a
category_idthat doesn't exist in thecategoriestable. It also prevents you from deleting a category if there are still items linked to it. - Avoid Duplication: Instead of typing "Electronics" over and over again in the items table, you just use the ID number (e.g.,
1). If you need to rename "Electronics" to "Tech", you only change it in one place!
Analogy:
If the Primary Key is a student's ID card, a Foreign Key is that same ID number written on a library book checkout log. It points back to the specific student who has the book.
Do you want to try inserting some data to see how this link works in practice?