Foreign keys enforce that a relationship between tables actually stays valid — you can’t reference a customer that doesn’t exist, and MySQL will stop you rather than silently allowing orphaned data.
CREATE TABLE orders (
id INT PRIMARY KEY AUTO_INCREMENT,
customer_id INT NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customers(id)
ON DELETE RESTRICT
ON UPDATE CASCADE
);
-- ON DELETE RESTRICT: block deleting a customer who has orders
-- ON DELETE CASCADE: deleting a customer deletes their orders too
-- ON DELETE SET NULL: deleting a customer nulls out customer_id on their orders
Choose the ON DELETE behavior deliberately per relationship — CASCADE is convenient but dangerous if applied carelessly (deleting one row silently deletes a whole tree of related data), while RESTRICT forces an explicit decision at delete time, which is usually the safer default for anything valuable.