What is a Foreign Key?

QuestionsQuestions8 SkillsProDec, 23 2025
0124

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.

  1. In the categories table, category_id is the Primary Key. It uniquely identifies a category (like "Electronics" or "Furniture").
  2. In the inventory_items table, you also have a category_id column. 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_id that doesn't exist in the categories table. 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?

0 Comments

no data
Be the first to share your comment!