Foreign keys
A foreign key in a database table is a field whose values are required to match corresponding primary key values, usually in another table. In the database defined previously, we would specify the foreign key Departments.Director
to reference the primary key Employees.ID
. So, for example, the Director of Data Analysis has the ID
15584, which identifies John Baker in Table 5-1.
Note that once a foreign key is designated in a table, no row may be added to it unless that key value matches an existing primary key value in the referenced table. Every row in the Departments
table must have a Director
value that matches an existing ID
value in the Employees
table.
When a foreign key in table A references a primary key in table B, we call A the child table and B the parent table. In this example, the Departments
table is the child and the Employees
table is the parent. Every child (Departments.Director
) must have a parent (Employees.ID
), and the parent must exist before the child exists...