This issue is tormenting me for several hours . I am trying to populate an AggregateResult list with the results of a query, but the query returns only nulls. The SAME CODE, run in Execute Anonymous, executes correctly and returns what is needed. Any ideas?

    List<GroupMember> users = new List<GroupMember>(
            [ Select UserOrGroupId From GroupMember Where GroupId IN ( Select ID from                Group Where Name = 'IT Department' )

    List<ID> ids = new List<ID>();
    for(Integer i=0;i < users.size() ; i++) ids.add(users[i].UserOrGroupId);

    AggregateResult[] owners = [Select OwnerID,COUNT(Name)NumberOfAssignees From Employee__c WHERE OwnerID IN :ids GROUP BY OwnerID];
  • Can you include the output you see from System.debug(owners); in your question? And say whether you are running this code from a controller, trigger or unit test?
    – Keith C
    Jul 24, 2014 at 22:06

2 Answers 2


If you are running this code in a controller with sharing or any other user context sharing rules and record access will be coming into force and thus potentially returning no results!

The execute anonymous harness runs the code as System and thus will have access to all records.

Try defining your class explicitly without sharing (unless this has other serious ramifications within your business!) to allow it to access all object/fields/records in your org.

public without sharing class abc {


If the AggregateResult is null, that means ids has no elements. Try debugging ids to make sure it contains what's you think it should.

  • Ids returns what is needed. It's correct
    – Bianca
    Jul 26, 2014 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.