Linking Tables
A foreign key is a column whose values must match a key in another table. An orders table may have a customer id that must exist in the customers table. This rule is called referential integrity, and the database enforces it on every write.
What It Prevents
- You cannot insert an order for a customer that does not exist.
- You cannot delete a customer that still has orders, unless you choose a rule for it.
Cascade Options
When a referenced row changes, you pick the behavior:
- Cascade applies the change to child rows, so deleting a customer deletes their orders.
- Restrict blocks the change while children exist.
- Set null clears the child reference instead of deleting it.
Foreign keys add a small write cost because each insert checks the parent, and they usually want an index on the referencing column.
Key idea
Foreign keys make the database guarantee that references point to real rows, and cascade rules decide what happens to children when a parent changes.