Cascading Constraints — Complete Guide
Cascading Constraints — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MySQL Tutorial on Toolliyo Academy.
On this page
MySQL Tutorial · Lesson 28 of 100
Cascading Constraints
Basics → Advanced
Basics · 1 — SQL · ~6 min · MySQL — Joins & Relationships
What is this?
ON DELETE and ON UPDATE clauses on foreign keys tell MySQL what to do when parent rows change: RESTRICT, CASCADE, SET NULL, or SET DEFAULT.
Why should you care?
Deleting a customer might CASCADE delete their cart lines in dev sandboxes, but prod often RESTRICTs delete until orders archive.
See it live — copy this example
Run in MySQL Workbench or the mysql CLI.
CREATE TABLE order_items (
line_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
order_id INT UNSIGNED NOT NULL,
product_id INT UNSIGNED NOT NULL,
qty INT NOT NULL,
CONSTRAINT fk_oi_order
FOREIGN KEY (order_id) REFERENCES orders(order_id)
ON DELETE CASCADE
);
What happened?
- When an order row is deleted, InnoDB automatically deletes its order_items lines.
- Without CASCADE you must delete children first manually.
Practice next
- Create order_items with ON DELETE CASCADE.
- Insert order + lines.
- DELETE FROM orders WHERE order_id = X;
- Switch to ON DELETE RESTRICT and retry delete — error.
- Compare ON UPDATE CASCADE for rare PK changes.
Remember
CASCADE propagates deletes/updates. RESTRICT blocks parent delete if children exist. Pick policy per business rule.
DataFlow cart cleanup
Dev DB cascades cart lines when test order removed — prod uses soft delete instead.
Outcome: Teams match cascade policy to compliance needs.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!