Skip to content

Cascade Delete

Medium — good to knowDatabase

ELI5 — The Vibe Check

A cascade delete is when deleting one thing automatically deletes everything connected to it — like pulling a thread that unravels the whole sweater. Delete a user? All their posts, comments, likes, and notifications go with them. It's powerful and convenient but terrifying if misconfigured. One accidental cascade delete can turn your database into a very expensive empty file.

Real Talk

Cascade delete is a referential action in relational databases where deleting a parent record automatically deletes all dependent child records. Defined via ON DELETE CASCADE in foreign key constraints, it maintains referential integrity but can cause unintended mass data loss. Alternatives include ON DELETE SET NULL, ON DELETE RESTRICT, and soft delete patterns.

Show Me The Code

-- Define cascade delete
CREATE TABLE posts (
  id SERIAL PRIMARY KEY,
  user_id INT REFERENCES users(id) ON DELETE CASCADE,
  content TEXT
);

-- Deleting a user automatically deletes all their posts
DELETE FROM users WHERE id = 123;
-- All posts with user_id = 123 are now gone too!

-- Safer: restrict deletion if children exist
-- ON DELETE RESTRICT  -- prevents delete if posts exist
-- ON DELETE SET NULL  -- sets user_id to NULL instead

When You'll Hear This

"The cascade delete wiped 50,000 comments when we deleted one test user." / "Use ON DELETE RESTRICT in production — cascade deletes are footguns."

Made with passive-aggressive love by manoga.digital. Powered by Claude.