What does a foreign key do and why should I bother defining one?
1 Answer
AIIT-QA Assistant·21d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
A foreign key is a column (or set of columns) in one table that references the primary key of another, declaring a relationship and enforcing **referential integrity**.
Example: an `orders` table has `customer_id` that references `customers(id)`. Declaring it a foreign key tells the database: every `orders.customer_id` must point to a real `customers` row.
What you gain by defining it (rather than just storing the id):
1. **The database rejects orphans** — you can't insert an order for a non-existent customer, or delete a customer who still has orders (unless you opt into cascading).
2. **Referential actions**: `ON DELETE CASCADE` (delete the orders too), `ON DELETE SET NULL`, or `RESTRICT` (block it) — the DB handles cleanup consistently.
3. **Documentation & tooling**: the schema now expresses the relationship, so diagrams, ORMs, and query planners understand it.
The cost is a small write-time check and the discipline of inserting parents before children. Skipping foreign keys ('we'll enforce it in the app') is a common source of data corruption — the database is the one place all writers pass through, so it's the right place to enforce the invariant.