Lesson 20 of 30
67%
Foreign Keys
A foreign key is a pointer to another table's primary key.
It says this score belongs to that student.
Two tables
sql
Result
Query OK, 0 rows affected
Query OK, 0 rows affected
What the rule does
You cannot insert a score for a student_id that does not exist.
You cannot delete a student who still has scores, unless you plan a cascade.
sql
Result
Query OK, 1 row affected
Query OK, 1 row affected
Cannot add or update a child row: a foreign key constraint fails (`scores`, CONSTRAINT FOREIGN KEY (`student_id`) REFERENCES `students` (`id`))
Why bother
Without the key, a typo can orphan a row.
The foreign key is a seatbelt. It catches the bad write.
Tip: Name the column table_id, like student_id. Future you will thank you.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.