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.
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.
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.
000384953

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings.
Privacy Statement
Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.
Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.
Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.