SyntaxStudy
Sign Up
MySQL Referential Integrity with Foreign Keys
MySQL Intermediate 4 min read

Referential Integrity with Foreign Keys

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.

Example
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
);
Pro Tip

Prefer RESTRICT over CASCADE for DELETE to avoid accidental data loss.