Foreign KeyOptional for Informatics Practices
Every key so far worked inside one table. A foreign key is the first one that reaches across to another — and it is what finally makes a relational database relational in the everyday sense of the word.
1The problem it solves
Suppose you record which teacher teaches each subject, all in one table:
| code | subject | teacher | designation | phone |
|---|---|---|---|---|
| CS083 | Computer Science | Mohan Das | PGT | 9800011111 |
| IP065 | Informatics Prac. | Mohan Das | PGT | 9800011111 |
| MA041 | Mathematics | Tashi Bhutia | TGT | 9800022222 |
Mohan Das appears twice, and everything about him appears twice with him. If his phone number changes you must remember to fix every row. Miss one and the database now disagrees with itself — the duplication problem from the very first lesson.
2Split it into two tables
Keep teachers in one table and subjects in another. The subjects table stores only the teacher's id:
| id (PK) | name |
|---|---|
| 2 | Mohan Das |
| 3 | Tashi Bhutia |
| code | sname | id (FK) |
|---|---|---|
| CS083 | Computer Science | 2 |
| IP065 | Informatics Prac. | 2 |
| MA041 | Mathematics | 3 |
Mohan Das is now stored once. The subjects table points at him twice, using a number. Change his phone number in one place and both subjects are instantly correct, because there was only ever one copy.
3The definition
A foreign key is a column in one table that refers to the primary key of another table.
The one being pointed at. It holds the primary key. teachers here.
The one doing the pointing. It holds the foreign key. subjects here.
Unlike a primary key, a foreign key may repeat — Mohan Das teaches two subjects, so 2 appears twice — and it may be NULL, which simply means “no teacher assigned yet”.
4The database enforces it
This is the part worth seeing rather than being told. Once a column is declared a foreign key, MySQL will not let the link be broken. Try to add a subject taught by teacher 77, who does not exist:
Refused. And it works the other way too — you cannot delete a teacher while a subject still points at them:
insert and delete commands above, and the foreign key … references … line that creates the rule, all belong to the chapters ahead. They are shown here only so you can see that the rule is real and enforced, not a convention people agree to follow.5Recap
A column referring to the primary key of another table.
Parent holds the primary key; child holds the foreign key.
Unlike a primary key. One teacher can teach many subjects.
The database refuses any change that would leave the reference pointing at nothing.
A foreign key in a table refers to…
Which is true of a foreign key but NOT of a primary key?
In subjects(code, sname, id) where id is a foreign key to teachers(id), which action will MySQL refuse?