EXERCISE
1A Foreign Key links rows between tables and lets the database automatically enforce that relationships stay valid.
Save
The problem Foreign Keys solve:
Without a foreign key, nothing stops you from creating an order for a customer that doesn''t exist:
-- Without FK constraint, this silently succeeds with a ghost customer:
INSERT INTO orders (customer_id, total) VALUES (99999, 500);
-- customer_id 99999 doesn't exist — corrupt data, no error
Foreign Key in action:
-- Parent table:
CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
-- Child table with Foreign Key:
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT NOT NULL,
total DECIMAL(10,2),
FOREIGN KEY (customer_id) REFERENCES customers(id)
ON DELETE CASCADE -- if customer deleted, their orders are deleted too
ON UPDATE CASCADE -- if customer id changes, orders update automatically
);
ON DELETE options:
ON DELETE CASCADE -- delete child rows automatically (orders deleted with customer)
ON DELETE RESTRICT -- block deletion if child rows exist (default, safest)
ON DELETE SET NULL -- set FK column to NULL when parent deleted
> 💡 Key Insight: ON DELETE RESTRICT (the default) is usually what you want. It forces you to clean up child records first, preventing accidental data .