What is a SOQL For Loop (for (List<Account> accList : [SELECT ...])) and how does it help avoid Heap Size limits?
Answer
A SOQL for loop iterates directly over a query result. Salesforce retrieves records in chunks of 200 instead of loading everything into one list, which keeps heap usage low.
apex
for (List<Account> chunk : [SELECT Id, Name FROM Account]) {
// process up to 200 records at a time
update chunk;
}
The single-record form for (Account a : [SELECT ...]) also streams in chunks. The 50,000 query row limit still applies, but heap size is not blown by a huge list.
soqlapexheapperformance