🗃️Foreign Key
Also known as FK, Foreign Key Constraint
A column that points to a row in another table. The link is checked for you.
Think of it like
Think of it like a name tag on a lunch box that says whose it is. The tag must match a real pupil.
Example
Each order has a customer_id. When Jack tries to save an order for customer 99, who does not exist, the database says no.
Why it matters
They stop orders that point at customers who are gone.
Definition
Example code
sql
INSERT INTO orders (customer_id, total) VALUES (99, 5);
-- Error: FOREIGN KEY constraint failedCommon mistake
Key takeaways
- 1Points elsewhere. To a primary key in another table.
- 2Checked for you. No links to rows that do not exist.
- 3Ties tables together. The heart of a relational database.