QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Database structure

What happens to child records when a parent is deleted?

What happens to child records is set by the ON DELETE option of the foreign key, not by application code. NO ACTION (the default) and RESTRICT refuse the delete while child rows exist, CASCADE deletes them with the parent, SET NULL nulls the reference (the column must be nullable), SET DEFAULT sets the default. A cascade runs as a chain, so rows are counted in all dependent tables.

SQL · Constraints and indexes

A user was deleted and the whole history of their payments went with them. Is that intended?

The admin panel has a "Delete user" button. A tester presses it on an account with two accounts and nothing bad happens. A week later accounting cannot find this customer's payments: they were removed by a cascade. What happens to child records is decided not by application code but by the ON DELETE option on the foreign key. This lesson is about how to read it and which scenarios to check.

How it works and why. A foreign key guarantees that a reference does not dangle. So when the parent is deleted, the database must decide what to do with the rows that point to it. The options: NO ACTION (the default) and RESTRICT refuse the delete while child rows exist. The difference is subtle: NO ACTION is checked at the end of the statement and can be deferred to the end of the transaction (DEFERRABLE), while RESTRICT fires at once and cannot be deferred. CASCADE deletes the child rows together with the parent. SET NULL keeps them and clears the reference. SET DEFAULT sets the default value. Each option answers a business question: may a child exist without a parent.

Example: the same DELETE under different options. Accounts 1 and 2 belong to user 1, account 3 to user 2.

CREATE TABLE accounts (
  id      integer PRIMARY KEY,
  user_id integer NOT NULL
          REFERENCES users (id) ON DELETE CASCADE,
  balance numeric(12,2) NOT NULL
);
-- users: 1 = Ana, 2 = Bo
-- accounts: (1, user 1), (2, user 1), (3, user 2)
DELETE FROM users WHERE id = 1;

The accounts table before and after DELETE with CASCADE

before
iduser_idbalance
11100.00 lost
2150.00 lost
3270.00
after
iduser_idbalance
3270.00
Figure 1. Deleting one user silently took two accounts. A cascade does not report how many rows vanished.
-- the same with ON DELETE NO ACTION (the default)
DELETE FROM users WHERE id = 1;
-- ERROR:  update or delete on table "users" violates foreign
--         key constraint "accounts_user_id_fkey" on table "accounts"
-- DETAIL: Key (id)=(1) is still referenced from table "accounts".
-- (message shortened)

Note the chain. If transactions also reference accounts with CASCADE, deleting the user takes them as well. A user with 2 accounts and 100 transactions each gives 1 + 2 + 200 = 203 deleted rows from one command. With SET NULL it is different: the column must be nullable, otherwise the clearing itself violates NOT NULL and the delete fails with error 23502. And the rows left with an empty user_id ("orphans") break reports that JOIN and lose them.

Two legitimate delete policies

Hard

ON DELETE CASCADE

Child data is gone for good. Fits service data (tokens, drafts), not financial history.

Soft

deleted_at

The row stays and queries hide it. History survives, but every query needs the filter and the email must be freed.

Figure 2. The choice depends on requirements: what law or business says must be kept.

Soft deletion moves the complexity into queries and uniqueness:

UPDATE users SET deleted_at = now() WHERE id = 1;

-- email uniqueness among live rows only
CREATE UNIQUE INDEX users_email_live
  ON users (email) WHERE deleted_at IS NULL;

Limits and alternatives. A cascade in the database knows nothing about files, caches and external systems: rows vanished while document scans stayed in storage. Deleting a parent with CASCADE on an unindexed foreign key column can be slow, because for each parent the database looks for children by a full scan (see the lesson on indexes). For personal data the requirement may be the opposite: delete not only the row but all copies. Then the test checks complete erasure, not "nothing broke".

Common mistakes.

  • Testing only the deletion of a parent without children: ON DELETE does not fire and the rule stays unchecked.
  • Not counting rows before and after: a cascade shows nothing, vanished data is visible only in counters.
  • Treating "500 on delete" as normal: it should be a clear "there are linked accounts".
  • Forgetting "orphans" after SET NULL and soft-deleted rows in reports and search.
  • Checking on an empty database: the rule shows only on data with relations.

Check yourself

accounts.user_id has NOT NULL and ON DELETE SET NULL. What happens on DELETE of a user who has an account?

Answer

The delete fails: the database tries to set user_id = NULL but NOT NULL forbids it (23502). The combination is contradictory, a finding in the schema: either the column must be nullable or another option is needed.

A user has 2 accounts, each with 100 transactions. Both foreign keys have CASCADE. How many rows vanish after DELETE of this user?

Answer

203: 1 user, 2 accounts and 200 transactions. That is why before a cascade test you count rows in all dependent tables, not only the one being deleted.

In an interview. Junior: It is set by ON DELETE on the foreign key: RESTRICT and NO ACTION forbid the delete while child records exist, CASCADE deletes them with the parent, SET NULL clears the reference. I check that the behaviour matches the requirements. Middle/Senior: I count rows in all dependent tables before and after, because a cascade runs in a chain and reports nothing. Separately I check that history which must be kept is not lost, that no orphans remain after SET NULL, and that soft deletion does not break uniqueness and reports.

More articles in this chapter