System.QueryException: Aggregate query has too many rows for direct assignment, use FOR loop

Published in Not-So-Secret Diary

It's a surprise to me, I do not expect to receive the exception in the next code block. But it happened when a number of child records greater or equals to 200.

for (Account a : [SELECT Id, (SELECT Id FROM Contacts) FROM Account]) {
    System.debug(p.Contacts.size()); // throw exception			
}

Here is the way how you can avoid this exception, just use FOR to calculate a number of children. It’s not graceful, but it works.

for (Account a : [SELECT Id, (SELECT Id FROM Contacts) FROM Account]) {
    Integer numberOfContacts = 0;
    for (Contact c : a.Contacts) {
        numberOfContacts++;
    }
    System.debug(numberOfContacts);		
}

Useful links:

Tagged under: Salesforce SOQL Limits

Comments powered by CComment