SQL=WITH RECURSIVE tree(id, guid, name, description, parent, offers_count, level, pguid) as ( select id, guid, name, description, parent, offers_count, 1 as level, pguid from catalog_categories where (guid='') and ((deleted!=1) or (deleted is null)) union all SELECT cc.id, cc.guid, cc.name, cc.description, cc.parent, cc.offers_count, tree.level+1, cc.pguid FROM catalog_categories as cc JOIN tree ON cc.guid = tree.pguid where ((deleted!=1) or (deleted is null)) ) select * from tree order by level desc