Monday, 25 July 2016

Aggregate Query has too many rows for direct assignment, use FOR loop

"Aggregate query has too many rows for direct assignment, use FOR loop "

Have you even experience this error message? The implication is that, somewhere, your code included an aggregate query, and while it’s returning not enough rows to generate a governor limit error, it is somehow returning enough rows to generate this error.

As per this Salesforce doc, this exception is sometimes thrown when accessing a large set of child records of a retrieved sObject inside the loop, or when getting the size of such a record set. To avoid getting this exception, the best practice is to use a for loop to iterate over the child records.

Okay then, I try to use the for loop to iterate over the child records as follows:

The query runs just fine. But later, I wind up with another fatal  error:
INVALID_QUERY_LOCATOR: invalid query locator

This looks pretty hopeless - can't exceed limits, and there's no way to check if we're exceeding limits. 
After a lot of trial and error, I finally determined that I don't have any solutions to resolve this issue. The workaround is that using a try-catch like below: 

Or, if you know the child record IDs, please use the retrieve call instead.

What is an aggregate query?
The SOQL documentation doesn’t explicitly define the term “aggregate query,” but it does describe “aggregate function” by saying, “Aggregate functions include AVG(), COUNT(), MIN(), MAX(), SUM(), and more.” It’s the “and more” that is relevant here.
In the section on “Understanding Relationship Names, Custom Objects, and Custom Fields,” the SOQL documentation describes a query that traverses the parent-to-child relationship as a type of aggregate query. So even though our original query doesn’t use any aggregate functions, it’s considered an “aggregate query” because the sub-select clause traverses the parent-to-child relationship.

No comments:

Post a Comment

Back to Top

What I Can Help



Do you wanna share posts

I am always looking for writers that have something interesting to say about Salesforce. Whether you have a post in mind or would like to collaborate on one, get in touch! - Click Contact Me