I am trying to use Aggregate result and dynamic query. I have tried the below code and I did get 101 error. Please help me in optimizing this code to avoid hitting governor limits. The error is at line 6

enter image description here

  • Where do you intend to use this code?
    – Adrian Larson
    Sep 26, 2016 at 18:14

1 Answer 1


If you just want to get number of contacts per Account, you can use a sub-query:

for (Account record : [SELECT (SELECT Id FROM Contacts) FROM Account])
    system.debug(record.Id + ' - ' + record.Contacts.size());

Or just loop through one aggregate query:

for (AggregateResult aggregate : [
    SELECT AccountId, COUNT(Id) records FROM Contact GROUP BY AccountId
    system.debug(aggregate.get(AccountId) + ' - ' + aggregate.get('records'));
  • Hey @Adrian My requirement is not exactly this. To keep it simple, I have used the above example. If I still have to modify my code to avoid limits how can I do? Sep 26, 2016 at 18:15
  • 1
    I'm not sure how you expect anyone to be able to answer such a general question. If you narrow it down to something more specific, it might be possible to help you.
    – Adrian Larson
    Sep 26, 2016 at 18:21
  • salesforce.stackexchange.com/questions/142084/… I have posted this question. Please check my exact scenario Sep 26, 2016 at 18:22

You must log in to answer this question.

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