I spent weeks debugging an obscure Salesforce internal error that made no sense.
System.QueryException: Aggregate query has too many rows for direct assignment, use FOR loop
The query had 5 child records with a Long Text Area field and a few hundred records in a completely separate subquery with only Id selected.
No LTA. No RTA. Just IDs.
Yet the query was failing.
After opening a case with Salesforce Support and escalating to the Product Team, I got the official answer:
"Working as Designed."
The Apex runtime applies a shared CLOB budget across ALL child subqueries — even ones with no LTA/RTA fields. The reasoning: heap safety across the entire query tree.
I wasn't satisfied with that answer. So I ran dozens of tests across different field sizes and record counts and reverse-engineered the internal formula.
Here's what the runtime actually does:
Step 1 — sum up all declared LTA/RTA field lengths anywhere in the query (parent + every subquery)
Step 2 — derive a total children row budget:
FLOOR( 1000 / POW(2, MAX( CEILING(LOG2(totalClobLength / 32768)), 0 )) )
Which produces this table:
totalClobLength | Row budget
---------------
256 B - 32 KB | 1,000
32–64 KB | 500
64–128 KB | 250
128–256 KB | 125
256–512 KB | 62
Both empirical thresholds I observed matched this formula exactly.
Here's the flaw.
The row budget is calculated from LTA/RTA field sizes — and then applied to ALL child records across ALL subqueries, including those that select only Id.
A subquery like (SELECT Id FROM Children2__r) contributes zero bytes of CLOB content.
But each of its records still consumes one slot from the budget.
The budget is asking "how many rows can we safely load given the CLOB volume?"
Then it counts rows that carry no CLOB data at all toward that answer.
The fix is straightforward:
Apply the CLOB row budget only to subqueries that actually select LTA/RTA fields.
Records in (SELECT Id FROM ...) should not count against a heap limit derived from text field sizes.
I've submitted this to IdeaExchange:
"Fix Design Flaw in internal totalClobLength calculation"
If you've ever hit this error in a multi-relationship query — or you work with contracts, documents, or any domain with rich-text fields on parent objects — please vote.
https://ideas.salesforce.com/s/idea/a0BHp000017Jka1MAC/fix-design-flaw-in-internal-totalcloblength-calculation#Salesforce #Apex #SalesforceArchitect #SalesforceDeveloper #GovernorLimits
Incredible write-up and deep dive! Counting zero-byte ID subqueries against a CLOB-derived budget is a textbook design oversight. Heading over to the IdeaExchange to vote for this right now. Thanks for doing the heavy lifting to figure this out!
