Find your content:

Search form

You are here

Is there a way to Query Role Hierarchy?


Using the Web-Services SOAP API, I'd like to query for all UserRoles under the same Parent Role.

The only way I can think of doing this is by querying all Roles, then putting together a tree using the ParentRoleId field. Is there a better way?

Attribution to: Matt K

Possible Suggestion/Solution #1

Here is an alternative method based on (extracted from) Find My Salesforce Users by Role Hierarchy by Jeff Douglas.

Is it better than your proposed solution? Probably not. It will depend on how many user roles there are and how deep the tree is. If you have a large number of UserRoles with very few levels of nesting it may be more efficient to make a couple of SOQL calls rather than retrieving all the roles and then rebuilding the entire tree.

private static Set<ID> getAllSubRoleIds(Set<ID> roleIds) {

    Set<ID> currentRoleIds = new Set<ID>();

    // get all of the roles underneath the passed roles
    for(UserRole userRole :[select Id from UserRole where ParentRoleId 
         IN :roleIds AND ParentRoleID != null]) {

    // go fetch some more rolls!
    if(currentRoleIds.size() > 0) {

    return currentRoleIds;

And then you would get all the sub UserRoles for the parent UserRoleId with:

Set<Id> allSubRoleIds = getAllSubRoleIds(new Set<ID>{parentUserRoleId});


Just reread the question and picked up that you are using the Web Services API. You could still use exactly the same approach, but send the SOQL queries via SOAP rather than Apex.

It would pay to do some real world measurements about which performs best in your environment considering:

  • Can you cache the data?
  • Are you only ever interested in a subset of the parent Role Ids?
  • How many levels of nesting there are in the hierarchy?
  • How many UserRoles there are?

If you are only every interested in a subset of parent Ids and the nesting level is fairly shallow I'd look at just caching the values of interest and pulling them down with a few recursive calls. Otherwise, you will probably be better pulling all the possible data down in a query with possibly a follow up queryMore.

Attribution to: Daniel Ballinger
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content