MySQL
foreign key
cascade delete
database constraints
relational database

MySQL foreign key constraints, cascade delete

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Foreign keys with cascade delete help keep relational data consistent when parent rows are removed. Instead of writing manual cleanup logic for each related table, the database automatically deletes dependent rows. This can simplify application code, but it must be designed carefully to avoid unintended data loss.

How Cascade Delete Works

A child table references a parent table through a foreign key. With ON DELETE CASCADE, deleting a parent row deletes matching child rows automatically.

sql
1CREATE TABLE customers (
2  customer_id INT PRIMARY KEY AUTO_INCREMENT,
3  name VARCHAR(100) NOT NULL
4);
5
6CREATE TABLE orders (
7  order_id INT PRIMARY KEY AUTO_INCREMENT,
8  customer_id INT NOT NULL,
9  total DECIMAL(10,2) NOT NULL,
10  CONSTRAINT fk_orders_customer
11    FOREIGN KEY (customer_id)
12    REFERENCES customers(customer_id)
13    ON DELETE CASCADE
14);

If a customer row is removed, all related orders are removed by MySQL in the same operation context.

Demonstration

sql
1INSERT INTO customers (name) VALUES ('Ava');
2INSERT INTO orders (customer_id, total) VALUES (1, 19.99), (1, 29.99);
3
4SELECT COUNT(*) AS order_count FROM orders WHERE customer_id = 1;
5
6DELETE FROM customers WHERE customer_id = 1;
7
8SELECT COUNT(*) AS order_count_after_delete FROM orders WHERE customer_id = 1;

The second count returns zero when cascade delete is active.

Compare With Other Delete Actions

Common options include:

  • RESTRICT or NO ACTION: prevent parent delete while children exist.
  • SET NULL: set child foreign key to null if parent deleted.
  • CASCADE: delete children automatically.

Use the action that matches business semantics. Cascade is convenient but not always correct for audit sensitive datasets.

Engine And Index Requirements

In MySQL, foreign keys require InnoDB or another engine that supports referential integrity. Referenced columns should be indexed and types must match exactly between parent and child columns.

Mismatch in type, collation, or engine is a frequent reason foreign key creation fails.

Operational Considerations

Cascade delete can remove many rows quickly. In high volume systems, large cascades may lock tables or generate heavy replication traffic. Plan maintenance windows for bulk parent deletions and monitor transaction impact.

For critical data, combine cascades with soft delete strategies or archival tables when legal retention is required.

Migration Example

Adding cascade to an existing foreign key usually requires dropping and recreating the constraint.

sql
1ALTER TABLE orders
2DROP FOREIGN KEY fk_orders_customer;
3
4ALTER TABLE orders
5ADD CONSTRAINT fk_orders_customer
6  FOREIGN KEY (customer_id)
7  REFERENCES customers(customer_id)
8  ON DELETE CASCADE;

Run this in controlled migrations with backup and rollback planning.

Testing Strategy

Before production rollout:

  1. Seed parent and child records.
  2. Execute parent delete in staging.
  3. Verify expected child deletions and unaffected tables.
  4. Measure query timing and lock behavior.
  5. Confirm replication and audit logging outcomes.

Integration tests prevent surprises during schema changes.

Application Layer Coordination

Even when cascade delete is enabled, application services should still express deletion intent clearly. Log parent deletion operations with affected entity identifiers so downstream systems can trace why child records disappeared.

If your domain emits events, include deletion reason and actor metadata before executing the SQL delete. Cascade handles relational cleanup, but business observability still belongs in application logic.

For APIs, document that deleting a parent resource removes related children automatically. Hidden cascade behavior can surprise API consumers and lead to accidental data loss in integration environments.

Soft Delete Interaction

If your system uses soft delete flags, hard cascade delete may conflict with retention requirements. In that case, consider explicit service logic or triggers that update child flags instead of physically deleting rows.

Common Pitfalls

  • Enabling cascade where historical records should be retained.
  • Assuming cascade applies when foreign keys were not created successfully.
  • Forgetting engine and type compatibility requirements.
  • Running large cascade deletes without performance planning.
  • Not documenting deletion side effects for application developers.

Summary

  • ON DELETE CASCADE automates child cleanup for parent deletions.
  • It improves integrity and reduces manual delete logic.
  • Correct schema setup and engine compatibility are essential.
  • Evaluate data retention and operational impact before enabling cascade.
  • Validate cascade behavior with integration tests and staged migrations.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.