Foreign-key actions
◈ 2 cardsDecide what happens to children when a parent is deleted.
ON DELETE / ON UPDATE
A foreign key can specify what happens to dependent rows when the referenced row is deleted (or its key updated):
ON DELETE RESTRICT(default) — refuse the delete if children existON DELETE CASCADE— delete the children tooON DELETE SET NULL— keep the children but null out the reference
CREATE TABLE child (
id int PRIMARY KEY,
parent_id int REFERENCES parent(id) ON DELETE CASCADE
);
This is how you encode real-world rules — delete an order and its line items should go with it (CASCADE); delete a category and products should just lose their category (SET NULL).