Sub topic 11
SOQL for loops for large result sets
This chapter assumes you can write inline SOQL queries, know the difference between a List and a single sObject result, and know that each transaction has governor limits.
The problem with assigning to a list
When you assign a query to a List, Apex loads every returned record into memory at once. With a large result set, that can exceed the heap size limit (6 MB for synchronous Apex, 12 MB for asynchronous). A SOQL for loop avoids this by placing the query directly in the for statement.
Single-record syntax
Integer processed = 0;
for (Account a : [SELECT Id, Name FROM Account WHERE Industry = 'Technology']) {
processed++;
}
System.debug('Processed ' + processed + ' accounts');Behind the scenes, Salesforce opens a query cursor and retrieves records in chunks of 200. Only the current chunk is held in memory. The loop variable a still looks like a single record to you.
List-of-records syntax
If you declare the loop variable as a list, each iteration receives one whole chunk of up to 200 records.
Integer chunks = 0;
Integer rows = 0;
for (List<Account> batch : [SELECT Id, Name FROM Account]) {
chunks++;
rows += batch.size();
}
System.debug(chunks + ' chunks, ' + rows + ' rows');Use this form when you want to pass a list to a method or DML statement. It lets you work on 200 records at a time instead of one.
What a SOQL for loop does not change
- The query count. The whole loop counts as one SOQL query toward the limit of 100 for synchronous transactions.
- The row limit. Every record the loop retrieves still counts toward the limit of 50,000 rows per transaction. A SOQL for loop cannot get past that limit.
- The need for bulk safety. Putting another query inside the loop body still runs one query per iteration.
When to use it
| Situation | Choice |
|---|---|
| Small, bounded result you need to read more than once | Assign to a `List` |
| Large result you read once, record by record | Single-record SOQL for loop |
| Large result you pass to helper methods in groups | List-of-records SOQL for loop |
| More than 50,000 rows | Batch Apex with `Database.getQueryLocator` |
Common mistakes
- Expecting the loop to hold results afterward. Once the loop ends, the records are gone, so copy what you need into a collection inside the loop.
- Adding to the collection you are looping over. The query result is not a list you can change.
- Assuming memory use is unlimited. A collection that you fill inside the loop still takes up heap space.
Exercise
A synchronous transaction needs to read 120,000 Account records with a SOQL for loop. Will the loop avoid a limit error, and why or why not?
Show answer
No. The loop avoids heap problems because it fetches 200 records at a time, but each retrieved record still counts toward the 50,000-row limit per transaction. The transaction fails with a limit exception partway through. Use Batch Apex with Database.getQueryLocator, which can process far more rows.