Foreign Key

A foreign key is a column, or group of columns, in one table whose values must match the values of a key in another table. It is how the relational model records that two tables are related: a row in an orders table carries the customer’s identifier as a foreign key, pointing back at the matching row in the customers table.

The PostgreSQL documentation describes the constraint directly: a foreign key constraint specifies that the values in a column (or a group of columns) must match the values appearing in some row of another table, and it says this maintains the referential integrity between two related tables. Referential integrity means the database will refuse to store a reference to a row that does not exist, and will refuse, or cascade, the deletion of a referenced row.

The concept follows naturally from Codd’s relational model. Once normalization splits data across several tables, each linked by keys, foreign keys are the mechanism that lets the database guarantee those links remain valid. They turn what would otherwise be a loose convention, “this number is supposed to be a real customer,” into a rule the system enforces.

Foreign keys also give the database engine choices about what to do when the referenced data changes. A deletion of a parent row can be restricted (blocked while children exist), cascaded (the children are deleted too), or set to null, depending on how the relationship should behave. Together with primary keys, foreign keys are what allow normalized tables to be reassembled correctly by joins.