Tuesday 14 July 2015

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

           This exception is sometimes thrown when accessing a large set of child records (200 or more) of a retrieved sObject inside the loop, or when getting the size of such a record set. For example, the query in the following SOQL for loop retrieves child contacts for a particular account. If this account contains more than 200 child contacts, the statements in the for loop cause an exception.


  1. for (Account acct : [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account LIMIT 100])
  2. {
  3.         // Assigning inner query values to List, checking list size , null conditions within the for loop leads the query exception
  4.         List<Contact> contactList = acct.Contacts;  
  5.         Integer count = acct.Contacts.size();
  6.         if(acct.Contacts.size() > 0)
  7.         {
  8.        
  9.         }
  10.         if(acct.Contacts != null)
  11.         {
  12.        
  13.         }
  14. }


To avoid getting this exception, use a for loop to iterate over the child records, as follows.

  1. for (Account acct : [SELECT Id, Name, (SELECT Id, Name FROM Contacts)
  2.                     FROM Account LIMIT 100])
  3. {                                      
  4.     Integer count=0;
  5.     for (Contact c : acct.Contacts)
  6.     {
  7.         count++;
  8.     }
  9. }

Reference: 

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_loops_for_SOQL.htm

No comments:

Post a Comment

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...