Delete A Subtree With A Recursive CTE

Collect every descendant of a category with a recursive CTE, then delete the whole subtree in one statement that returns the removed rows.

SqlData Integrity

Code

snippet
-- 邻接表目录树:parent_id 指向上级,NULL 为根
CREATE TABLE categories (
    id        integer PRIMARY KEY,
    parent_id integer REFERENCES categories (id),
    name      text NOT NULL
);

INSERT INTO categories VALUES
    (1, NULL, 'Electronics'),
    (2, 1,    'Phones'),
    (3, 2,    'Smartphones'),
    (4, 2,    'Accessories'),
    (5, 1,    'Laptops'),
    (6, NULL, 'Books');

-- collect the subtree with a recursive CTE, then delete it in one statement
WITH RECURSIVE doomed AS (
    SELECT id FROM categories WHERE id = 2
    UNION ALL
    SELECT c.id
    FROM categories c
    JOIN doomed d ON c.parent_id = d.id
)
DELETE FROM categories
USING doomed
WHERE categories.id = doomed.id
RETURNING categories.id, categories.name;

-- 验证:只剩 1 Electronics、5 Laptops、6 Books
SELECT id, name FROM categories ORDER BY id;

How the snippet works

Several statements share this file — SELECT / INSERT / DELETE / CREATE, with categories and doomed among the objects involved.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; a RETURNING clause that hands the affected rows back to the caller; a UNION combining result sets from separate queries; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a foreign-key REFERENCES guard tying rows to the parent table.

Applying it

Run it in the categories database context.

Statements that matter

WITH RECURSIVE doomed AS (
SELECT id FROM categories WHERE id = 2
UNION ALL
SELECT c.id
FROM categories c
JOIN doomed d ON c.parent_id = d.id
)
DELETE FROM categories
USING doomed
WHERE categories.id = doomed.id
RETURNING categories.id, categories.name;
INSERT INTO categories VALUES
(1, NULL, 'Electronics'),
(2, 1,    'Phones'),
(3, 2,    'Smartphones'),
(4, 2,    'Accessories'),
(5, 1,    'Laptops'),
(6, NULL, 'Books');
CREATE TABLE categories (
id        integer PRIMARY KEY,
parent_id integer REFERENCES categories (id),
name      text NOT NULL
);

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`categories`, `doomed`, combined through a join.