Loading

Aggregate query has too many rows for direct assignment, use FOR loop' Salesforce Error

Julkaisupäivä: Jun 18, 2026
Kuvaus

The error "Aggregate query has too many rows for direct assignment, use FOR loop" occurs in Salesforce Apex when you attempt to directly assign the results of a parent-child SOQL query to a variable when the child relationship returns too many rows.
For example, the following SOQL query retrieves an Account record along with all of its related Contacts:

Select name, (Select firstname,lastname From Contact) From Account limit 1


If the Account has thousands of related Contacts, Salesforce throws this error because the child record set is too large to be directly assigned to a variable. Salesforce enforces governor limits on direct assignment of subquery results to prevent excessive memory usage.

Ratkaisu

Solution 1: Use a FOR Loop to Iterate Child Records

Instead of directly assigning the entire child collection to a variable, use a FOR loop to iterate through child records one at a time. This avoids the direct assignment row limit.

for (childtype ch : Parent.children) {

//do some logic...

}

In this pattern, Parent.children refers to the child relationship collection on the parent record. Each iteration of the loop processes one child record, keeping memory usage within governor limits.

Solution 2: Use a Map of Parent to Child Objects

Alternatively, build a map of parent records to their child collections and use .size() on individual map keys rather than on the full child relationship directly.
Instead of:

if (parent.child.size() > 0)

Use a map-based approach to check the size of child collections per parent record. This avoids the direct assignment error by not attempting to load the entire child collection into a single variable.

Knowledge-artikkelin numero

000384953

 
Ladataan
Salesforce Help | Article