Primary And Foreign Keys
Keys are how a relational database enforces identity and references between tables.
A primary key uniquely identifies each row in a table. It must be unique and not null, and most databases build an index on it automatically. No two rows may share the same primary key value.
A foreign key is a column in one table that points at the primary key of another. It says rows here belong to a row there. The database enforces referential integrity, meaning a foreign key value must match an existing parent row or be null.
Referential integrity protects you from orphans. If you try to delete a parent row that children still reference, the database can:
- Restrict the delete and raise an error
- Cascade the delete to the children
- Set null on the children that referenced it
Choosing the right rule encodes business meaning. Cascading from an order to its line items makes sense, since the items have no life without the order. Restricting deletes on a customer who still has orders protects history.
Together these keys turn a pile of tables into a connected, trustworthy graph where every reference resolves.
Key idea
A primary key uniquely names each row, and a foreign key references one, letting the database enforce that every link points at a real parent.