LearnContact
Lesson 1618 min read

Foreign Key

Learn what a foreign key is and how it links two tables together by referencing another table's primary key.

Introduction

Real applications rarely keep all their data in one single table. A school database might have a students table and a separate grades table, and the two need a reliable way to stay connected. That connection is built using a foreign key.

In this lesson, you will learn what a foreign key is, build a worked example linking two tables, and see what MySQL does when a foreign key rule would be broken.

What You Will Learn
  • What a foreign key is and what problem it solves.
  • How to create a table with a foreign key referencing another table's primary key.
  • What happens when you try to insert an invalid foreign key value.
  • What ON DELETE CASCADE does.

What is a Foreign Key?

A foreign key is a column (or set of columns) in one table that references the primary key of another table. It creates a link between the two tables, ensuring that the value stored actually corresponds to a real row in the other table.

For example, if a grades table stores a student_id for every grade, a foreign key ensures that every student_id used actually matches a real, existing student in the students table — you cannot record a grade for a student who does not exist.

Note

The table containing the foreign key (grades) is often called the "child" table, and the table it references (students) is often called the "parent" table.

Worked Example: Linking Two Tables

Let's build a students table and a grades table, where each grade references exactly one student through a foreign key.

CREATE TABLE students (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    age INT,
    grade VARCHAR(2)
);

CREATE TABLE grades (
    id INT PRIMARY KEY,
    student_id INT,
    subject VARCHAR(50),
    score INT,
    FOREIGN KEY (student_id) REFERENCES students(id)
);
Result
Query OK, 0 rows affected
Query OK, 0 rows affected

The FOREIGN KEY (student_id) REFERENCES students(id) clause tells MySQL: every value stored in grades.student_id must match an existing value in students.id.

INSERT INTO students (id, name, age, grade) VALUES (1, 'Alex', 16, 'A');
INSERT INTO students (id, name, age, grade) VALUES (2, 'Sam', 17, 'B');

INSERT INTO grades (id, student_id, subject, score) VALUES (1, 1, 'Math', 92);
INSERT INTO grades (id, student_id, subject, score) VALUES (2, 2, 'Science', 88);
Result
Query OK, 1 row affected
Query OK, 1 row affected
Query OK, 1 row affected
Query OK, 1 row affected
idstudent_idsubjectscore
11Math92
22Science88

What Happens on an Invalid Reference

Now let's try inserting a grade for a student_id that does not exist in the students table.

INSERT INTO grades (id, student_id, subject, score)
VALUES (3, 99, 'History', 75);
Error
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`school`.`grades`, CONSTRAINT `grades_ibfk_1` FOREIGN KEY (`student_id`) REFERENCES `students` (`id`))

MySQL rejects the insert because there is no student with id 99 in the students table. This is the foreign key constraint doing its job — it refuses to let the grades table reference a student that does not exist, keeping the two tables consistent with each other.

ON DELETE CASCADE

By default, MySQL also prevents you from deleting a row from students if any grade in the grades table still references it, since that would leave behind a grade pointing at a student that no longer exists.

Sometimes, though, you want related rows to be cleaned up automatically. Adding ON DELETE CASCADE to a foreign key tells MySQL: if the referenced student row is deleted, automatically delete every grade row that referenced it too.

CREATE TABLE grades (
    id INT PRIMARY KEY,
    student_id INT,
    subject VARCHAR(50),
    score INT,
    FOREIGN KEY (student_id)
        REFERENCES students(id)
        ON DELETE CASCADE
);

With this in place, deleting a student automatically removes their grades along with them, instead of blocking the delete or leaving orphaned rows behind.

Note

ON DELETE CASCADE is powerful, but it means a single DELETE on a parent table can silently remove rows in other tables too. Use it deliberately, and only where that automatic cleanup is genuinely what you want.

Common Mistakes

Avoid These Mistakes
  • Forgetting to create the referenced (parent) table before the table containing the foreign key.
  • Trying to insert a foreign key value that does not exist yet in the referenced table.
  • Adding ON DELETE CASCADE without fully considering what related data it will remove automatically.
  • Assuming a foreign key alone makes a column unique — it does not, unless combined with its own UNIQUE or PRIMARY KEY constraint.

Best Practices

  • Always create the parent table (with its primary key) before the child table that references it.
  • Name foreign key columns clearly, like student_id, so the relationship is obvious at a glance.
  • Use ON DELETE CASCADE only when automatically removing related rows is truly the desired behavior.
  • Check that a referenced row actually exists before inserting a row that points to it.

Frequently Asked Questions

Can a foreign key reference a column that is not a primary key?

Yes, technically it can reference any column with a UNIQUE constraint, but referencing the primary key of the parent table is by far the most common and recommended approach.

Can a foreign key column contain NULL?

Yes, unless it also has a NOT NULL constraint. A NULL foreign key value simply means that row does not reference any row in the parent table.

What happens if I do not use ON DELETE CASCADE?

By default, MySQL blocks the deletion of a parent row if any child row still references it, protecting you from leaving behind broken references.

Can two tables have foreign keys pointing at each other?

Yes, though it requires careful planning, since each table then depends on the other existing first. This is an advanced pattern beyond the scope of this lesson.

Key Takeaways

  • A foreign key is a column that references the primary key of another table, linking the two together.
  • FOREIGN KEY (column) REFERENCES table(column) defines the link when creating a table.
  • Inserting a foreign key value with no matching row in the referenced table causes a constraint violation error.
  • ON DELETE CASCADE automatically deletes related child rows when the referenced parent row is deleted.
  • Foreign keys keep relationships between tables accurate and trustworthy.

Summary

A foreign key is how two tables stay meaningfully connected. By requiring every referenced value to actually exist in the parent table, MySQL prevents broken, dangling relationships between your data.

In this lesson, you learned what a foreign key is, built a students and grades example linked by student_id, saw what happens on an invalid reference, and previewed ON DELETE CASCADE. Next, you will learn about the UNIQUE key constraint.

Lesson 16 Completed
  • You understand what a foreign key is and why it matters.
  • You can create a table with a foreign key referencing another table.
  • You know what error occurs when a foreign key reference is invalid.
  • You understand what ON DELETE CASCADE does.
Next Lesson →

Unique Key