With a table with a self-referential foreign key:
CREATE TABLE tree (
id INTEGER,
parent_id INTEGER,
PRIMARY KEY (id)
);
ALTER TABLE tree
ADD CONSTRAINT fk_tree
FOREIGN KEY (parent_id)
REFERENCES tree(id);
INSERT INTO tree (id, parent_id)
VALUES (1, null),
(2, 1),
(3, 1),
(4, 2),
(5, null),
(6, 5);
I wish to delete a branch by recursively traversing the tree as I may not use ON DELETE CASCADE
.
WITH RECURSIVE branch (id, parent_id) AS (
SELECT id, parent_id
FROM tree
WHERE id = 1 -- Delete branch with root id = 1
UNION ALL SELECT c.id, c.parent_id
FROM tree c -- child
JOIN branch p -- parent
ON c.parent_id = p.id
)
DELETE FROM tree t
USING branch b
WHERE t.id = b.id;
Is it safe to do it with a common table expression in Postgres, or do I have to worry about the order in which the records are deleted? Will Postgres delete all rows as a single set, or one by one?
If the answer is dependent on version, from which version is the deletion safe?