We're working in a managed package that leverages SOQL aggregate functions and we want to ensure we are considering governor limits appropriately. To prepare for it we have created a Scratch Org with 2 accounts and around 50k related opportunities each.

SELECT COUNT(Id) oppCount, AccountId FROM Opportunity GROUP BY AccountId

────────  ──────────────────
50089     0011x000014xu2PAAQ
48800     0011x000014ydkxAAA

The docs state the following regarding SOQL aggregate functions:

Queries that include aggregate functions are still subject to the limit on total number of query rows. All aggregate functions other than COUNT() or COUNT(fieldname) include each row used by the aggregation as a query row for the purposes of limit tracking.

Executing the query directly in Apex like so seems to respect the above mentioned premise

Aggregateresult[] res = [SELECT SUM(Amount) sumOpps, AccountId FROM Opportunity GROUP BY AccountId];

 ▸    ERROR: System.LimitException: Too many query rows: 50001
 ▸    ERROR: AnonymousBlock: line 1, column 1

However, executing the same query directly in the developer console (or via API) or executing in Apex using a for-loop seems to work:

SELECT SUM(amount) oppSum, AccountId FROM Opportunity GROUP BY AccountId

──────  ──────────────────
732000  0011x000014ydkxAAA
676336  0011x000014xu2PAAQ

for (Aggregateresult res : [SELECT SUM(Amount) sumOpps, AccountId FROM Opportunity GROUP BY AccountId]) {

11:49:18.22 (22562623)|USER_INFO|[EXTERNAL]|0051x000003srSh|test-fynshi2zxclh@example.com|(GMT+02:00) Central European Summer Time (Europe/Paris)|GMT+02:00
11:49:18.22 (22611799)|EXECUTION_STARTED
11:49:18.22 (22618498)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
11:49:18.22 (192762667)|USER_DEBUG|[2]|DEBUG|AggregateResult:{sumOpps=732000.0, AccountId=0011x000014ydkxAAA}
11:49:18.22 (192825300)|USER_DEBUG|[2]|DEBUG|AggregateResult:{sumOpps=676336.0, AccountId=0011x000014xu2PAAQ}

Can someone please explain the reasoning behind this and how the limits are applied for these cases?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.