Agent Wranglers

DAT-6Recommended

Plan how rows are removed

Decide for each table what deleting means, and make the foreign keys say it.

How to do it

Use ON DELETE CASCADE for rows that only exist as part of a parent, such as order lines. Use RESTRICT where a delete must be stopped. With a deleted_at column for soft deletes, every query must filter on it. Make unique indexes partial, with WHERE deleted_at IS NULL, so a deleted email can sign up again. Personal data must still be erased when the law asks, as the data requests rule says.

Examples

SQL example

CREATE TABLE order_lines (
  order_id bigint NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
  product_id bigint NOT NULL REFERENCES products (id) ON DELETE RESTRICT,
  quantity int NOT NULL CHECK (quantity > 0)
);
-- With soft deletes, uniqueness applies to live rows only
CREATE UNIQUE INDEX customers_email_live ON customers (lower(email)) WHERE deleted_at IS NULL;

How to check

Delete a test parent row. Its owned rows disappear, protected references block the delete, and no orphan rows remain.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/schema-design/deletion-design">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.