For example... I have a SOQL query :-

[SELECT name, profile.name, email, isActive 
 from User 
 where UserRoleId in 
      (SELECT ID from UserRole WHERE name in ('CEO','COO','ALC Midwest','ALC Southwest'))

Now each role may have more than one users.

So, My requirement is that I want a map with key = UserRoleID and value = list of all users under that role.

So is it possible to do this without looping the above query's result and then putting values into map

Or some GROUP BY clause (or something else) can help me do this efficiently..

If nothing is possible and only looping is the only way then please provide an efficient and optimized code than the normal one-by-one row looping.

Help me its urgent

1 Answer 1


You can create this map:

Map<Id, UserRole> m = new Map<Id, UserRole>([
        select Id, (select UserName, ProfileId from Users order by UserName)
        from UserRole

and then the list of users would be:

Id userRoleId = ...;
User[] users = m.get(userRoleId).Users;
  • SOQL query always return Map<Id, ObjectName> so if we can assign soql query to such map so unnecessary "for-loop" can be avoid.
    – Ankuli
    Commented Jul 23, 2015 at 10:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .