WITH RECURSIVE with_decendants(id, parent, name, content, level) AS ( VALUES(2, 1, '', '', 0) UNION ALL SELECT notes.id, notes.parent, notes.name, notes.content, with_decendants.level+1 FROM notes, with_decendants WHERE notes.parent=with_decendants.id ) SELECT * FROM with_decendants;