Foreign Keys & Relationships
Link tables with a FOREIGN KEY so every order points at a real customer, and choose what happens on delete.
A foreign key points at another table
A foreign key is a column whose values must match a row in another table. Here orders.customer_id must match a real customers.id. This guarantee is called referential integrity.
If you do not name the column in the other table, PostgreSQL uses its primary key. A NULL in the foreign key column is allowed and skips the check, unless you also add NOT NULL.
One customer with many orders is a one-to-many relationship. A many-to-many relationship, such as students and courses, needs a third table with a foreign key to each side.
No orphan rows
Without a foreign key, an order could point at customer 99 who does not exist. Reports would break and nobody would know why.
With a foreign key, the database refuses the bad order for you, every time, from every program that writes to it.
Declare the link and choose the delete rule
Add REFERENCES to the column. The optional ON DELETE part says what happens to orders when their customer is deleted:
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer
REFERENCES customers (id)
ON DELETE NO ACTION,
item text
);Inserting an order for customer 99 fails: insert or update on table "orders" violates foreign key constraint. The detail says the key is not present in table customers.
The delete rules: NO ACTION (the default) refuses to delete a customer who still has orders. RESTRICT does the same and cannot be postponed. CASCADE deletes the orders too. SET NULL keeps the orders and clears customer_id.
Break the link, then change the rule
Try an order for customer 99, then delete customer 1 under each ON DELETE rule and watch what happens to the orders.
| idinteger | nametext | citytext | ageinteger |
|---|---|---|---|
| 1 | Asha | Pune | 31 |
| 2 | Ben | Leeds | 17 |
| 3 | Chen | Oslo | NULL |
| 4 | Dara | Lima | 24 |
| 5 | Eli | Rome | NULL |
| idinteger | customer_idinteger | itemtext |
|---|---|---|
| 101 | 1 | Notebook |
| 102 | 1 | Pen |
| 103 | 2 | Ruler |
NO ACTION (the default) refuses to delete a customer who still has orders. RESTRICT does the same, and cannot be postponed.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A foreign key requires each non-NULL value to match a row in the table it references.
- NO ACTION and RESTRICT block deleting a referenced row, CASCADE deletes the children, and SET NULL clears the link.
- A many-to-many relationship needs a junction table with two foreign keys.
- PostgreSQL does not index a foreign key column for you, so add an index when you query or delete by it.
Done with this concept?
Mark it complete to track your progress. No login needed.