function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Paul BerglundPaul Berglund 

Is there a better way to build a territory hierarchy?

I'm starting at the 4th level from the bottom and trying to build a territory hiearchy.  What I'm seeing is I need to query the child territories one group at a time by getting the territories where the ParentTerritoryId = the starting territory Id, and doing multiple subqueries for each level below.

4th level territory = select Id, Name from Territory where id = :id;
3rd level territories = select Id, Name from Territory where ParentTerritoryId = 4th level territory id;
Build a map of all the Ids - called 3rd level territory ids
2nd level territories = select Id, Name from Territory where ParentTerritoryId in :3rd level territory ids;
Build a map of all the Ids - called 2nd level territory ids
1st level territories = select Id, Name from Territory where ParentTerritoryId in :2nd level territory ids;

Is there a more efficient way of doing this?