You just need to ensure that you have set up a foreign key from the child row to its parent, with the ON DELETE CASCASDE
option set on the foreign key. This works equally well a self referencing table as it does to references in separate tables. In order to delete the tree, simply delete the parent node. All child rows will be summarily deleted.
e.g. Given:
CREATE TABLE MyTable
(
ID INT NOT NULL PRIMARY KEY,
ParentID INT NULL,
CONSTRAINT FK_MT_Parent FOREIGN KEY (ParentID) REFERENCES MyTable(ID) ON DELETE CASCADE
);
-- And inserting two trees of data:
-- 1-2-3
-- └-4
-- 10 - 11
INSERT INTO MyTable(ID,ParentID) VALUES
(1,null), (2,1), (3,2), (4,2),
(10,null), (11,10);
We can remove the whole of the first tree by simply deleting the root node:
DELETE FROM MYTable WHERE ID = 1;
SqlFiddle of same
Note however that from the Docs that there is a limit to the depth of CASCADE
deletes:
Cascading operations may not be nested more than 15 levels deep