// SQL snippet

Preview what a delete would cascade

Count the rows at each level that reference the target id: the exact set an ON DELETE CASCADE would take with it.

Main statement
All engines

The task

Deleting a customer with ON DELETE CASCADE in place removes their orders and every order line. Run the preview first: the counts tell you whether the delete is a cleanup or an accident.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT c.id AS customer_id, c.email,
 (SELECT COUNT(*) FROM orders o
  WHERE o.customer_id = c.id) AS orders_deleted,
 (SELECT COUNT(*) FROM order_items oi
  JOIN orders o ON o.id = oi.order_id
  WHERE o.customer_id = c.id) AS order_items_deleted
FROM customers c
WHERE c.id = 42;

工作原理

Two correlated subqueries count the damage per level: direct children (orders) and grandchildren reached through the children (order_items). The customer row itself is not counted. Add one subquery per further table that cascades, following the same join path. For a batch delete, the variant sums the impact over a list of ids in one pass; COUNT(DISTINCT o.id) is needed there because the join repeats each order once per line.

Variations

Totals for a batch of customers

SELECT COUNT(DISTINCT o.id) AS orders_deleted,
       COUNT(oi.id) AS order_items_deleted
FROM orders o
LEFT JOIN order_items oi ON oi.order_id = o.id
WHERE o.customer_id IN (42, 43, 44);

Questions that come up

What if the FK has no ON DELETE CASCADE?

Then the DELETE fails on the first child row. The preview still matters, because it tells you how much manual cleanup the delete needs to succeed. Use the same counts to plan the order of deletes (children first), or switch the strategy to soft delete, which the soft-delete-audit recipe tracks.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.