With PathTree (id, parent_id, Label, depth) AS ( Select ID, ParentId, Label, 0 as depth From Entity Where parentid is null Union all Select e.ID, e.ParentId, e.Label, pt.depth+1 as depth from PathTree pt Join Entity e on (pt.ID = e.parentid) )