liveBook · Manning

Cascading delete

As explained in Grokking Relational Database Design

CASCADE is a referential action that automatically propagates parent-row deletions or key updates to corresponding child rows.

A cascading delete automatically removes child-table rows when their related row in a parent table is deleted. It preserves referential integrity by preventing orphaned child rows. section 6.13

Choose the referential action that matches the data relationship:

  • Use ON DELETE CASCADE when child rows should disappear with the parent. section 6.13
  • Use ON DELETE RESTRICT or NO ACTION when deleting the parent must be prevented. section 6.13
  • Use ON DELETE SET NULL when the child rows should remain but their foreign keys should be cleared. section 6.13

Payment methods linked to users

A payment_method table can delete its payment records automatically when the referenced user is deleted: FOREIGN KEY (email) REFERENCES user (email) ON DELETE CASCADE ON UPDATE CASCADE. section 6.13

  -- comment: works for MySQL, MariaDB and PostgreSQL
  -- comment: see the code repo for other RDBMS
  CREATE TABLE payment_method (
    payment_id INT PRIMARY KEY,
    name VARCHAR(30) NOT NULL,
    card_number CHAR(16) NOT NULL,
    expiry_date CHAR(4) NOT NULL,
    email VARCHAR(320) NOT NULL,
    CONSTRAINT fk_payment_method_user
      FOREIGN KEY (email) REFERENCES user (email)
      ON DELETE CASCADE
      ON UPDATE CASCADE
  );

View a concrete foreign-key definition containing both cascading delete and cascading update actions. section 6.13

How Grokking Relational Database Design covers it

How deep it goes
Defines automatic effects and shows foreign-key clauses, but does not detail execution internals.
Examples
Uses payment methods linked to users and company devices linked to employees to compare deletion outcomes.
What it assumes
Assumes parent-table, child-table, primary-key, and foreign-key relationships, while defining their deletion effects.
What you can do after
Operate/configure it by adding ON DELETE CASCADE to a foreign-key constraint.
How it connects
Connects cascading delete with foreign keys, parent tables, child tables, referential integrity, cascading update, and SET NULL.

Also explained in

Compare how 3 books explain cascading delete →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Relational Database Design. The section links point to the parts of the book it draws on.