Referential Integrity
Foreign keys enforce referential integrity: a FK value must exist in the parent table. Configure cascade behavior with ON DELETE and ON UPDATE.
Foreign keys enforce referential integrity: a FK value must exist in the parent table. Configure cascade behavior with ON DELETE and ON UPDATE.
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customers(id)
ON DELETE RESTRICT -- prevent deleting customer with orders
ON UPDATE CASCADE -- update FK if PK changes
);
Prefer RESTRICT over CASCADE for DELETE to avoid accidental data loss.