TransWikia.com

SOQL Aggregate functions circumventing limits?

Salesforce Asked by jonathanwiesel on December 10, 2021

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

OPPCOUNT  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

OPPSUM  ACCOUNTID
──────  ──────────────────
732000  0011x000014ydkxAAA
676336  0011x000014xu2PAAQ

for (Aggregateresult res : [SELECT SUM(Amount) sumOpps, AccountId FROM Opportunity GROUP BY AccountId]) {
    System.debug(res);
}

11:49:18.22 (22562623)|USER_INFO|[EXTERNAL]|0051x000003srSh|[email protected]|(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?

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP