Sub topic 11
SOQL for loops for large result sets
This chapter covers the SOQL for loop, a loop form that retrieves query results in batches instead of building one large list. It assumes you can write inline queries, use bind variables, and read a governor limit error. You should also know the difference between List<Account> and a single Account.
The problem with assigning a query to a list
When you assign a query to a list, Apex retrieves every matching row and holds all of them in memory at once.
List<Account> accts = [SELECT Id, Name, Description FROM Account];Memory for a transaction is capped by the heap size limit. That limit is 6 MB for synchronous code and 12 MB for asynchronous code. A query that returns thousands of rows with long text fields can exceed it and fail with a System.LimitException: Apex heap size too large.
A SOQL for loop avoids this. Apex fetches a chunk of rows, runs your loop body, then fetches the next chunk. The earlier chunks can be released from memory.
Two forms of the loop
The query goes directly in the for statement, in square brackets. The form depends on the type of the loop variable.
Single-record form
The loop variable is one sObject. The body runs once per record.
Integer processed = 0;
for (Account a : [SELECT Id, Name FROM Account WHERE Industry = 'Technology']) {
processed++;
}
System.debug('Processed ' + processed + ' accounts');Behind the scenes, Apex retrieves records from the database in chunks of 200 and hands them to you one at a time. This is the simplest form. It works well when you only read each record or do light work on it.
List form
The loop variable is a List of the sObject type. The body runs once per chunk, and each chunk holds up to 200 records.
Integer chunks = 0;
Integer rows = 0;
for (List<Account> batch : [SELECT Id, Name FROM Account WHERE Industry = 'Technology']) {
chunks++;
rows += batch.size();
}
System.debug(rows + ' rows in ' + chunks + ' chunks');Use this form when you want to do something once per group of records. The most common case is DML.
Why the list form matters for DML
Calling DML inside the single-record form usually leads to one DML statement per record. That fails quickly against the limit of 150 DML statements per transaction.
// Anti-pattern: one DML statement per record
for (Account a : [SELECT Id FROM Account WHERE Industry = 'Technology']) {
a.Description = 'Reviewed';
update a;
}The list form lets you update a whole chunk with one statement.
Integer updated = 0;
for (List<Account> batch : [
SELECT Id, Description FROM Account WHERE Industry = 'Technology'
]) {
for (Account a : batch) {
a.Description = 'Reviewed';
}
update batch;
updated += batch.size();
}
System.debug('Updated ' + updated + ' accounts');This code uses one DML statement per 200 records. The outer loop is the batch, and the inner loop is an ordinary loop over a list.
You can also collect changes across the whole loop and run one DML statement at the end. That uses the fewest DML statements, but the list of changed records then grows in the heap. This partly cancels the memory saving. The choice is between fewer DML statements and lower memory use.
What a SOQL for loop does and does not change
A SOQL for loop saves heap memory. It does not remove the other governor limits.
| Limit | Effect of a SOQL for loop |
|---|---|
| Heap size | Reduced pressure, because only one chunk is needed at a time |
| Number of SOQL queries (100 synchronous) | No change. The whole loop counts as one query. |
| Total rows retrieved by SOQL (50,000) | No change. Every row you iterate counts. |
| DML statements (150) and DML rows (10,000) | No change. The list form helps you stay under them. |
| CPU time (10,000 ms synchronous) | No change. Your loop body still costs CPU time. |
The 50,000-row limit is the one most often misunderstood. A SOQL for loop makes large results fit in memory, but a query that matches more than 50,000 rows in one transaction still throws a LimitException. If you need to process more rows than that, use Batch Apex. It is covered in other material and is not part of this chapter.
Rules for writing a SOQL for loop
The query must be written inside the for statement. Apex only treats the loop as a SOQL for loop when the bracketed query is the thing being iterated.
// This is a SOQL for loop: records arrive in chunks
for (Account a : [SELECT Id FROM Account]) {
// ...
}
// This is NOT a SOQL for loop: the whole query result is loaded first
List<Account> all = [SELECT Id FROM Account];
for (Account a : all) {
// ...
}The second form is a common mistake. It loops fine, but all rows are already in memory before the loop starts, so you gain nothing.
Other points to remember:
- Bind variables work as in any inline query.
WHERE Industry = :industryis valid inside theforstatement. - The query can contain a relationship subquery or parent fields. The records in each chunk carry those values.
- Ordering still applies. Add
ORDER BYif the order in which you process records matters, because without it the order is not guaranteed. - Do not rely on
LIMITto avoid heap problems if you also need all rows.LIMITstops the loop early, so it is only appropriate when you really want a subset. - Declare the variable type to match the query. The single-record variable must be the sObject type, and the list variable must be a
Listof that type. A mismatch is a compile error.
Changing records inside the loop
In the list form, you can change the field values of records in the chunk and then call update batch, as shown earlier. You can also build a separate list of records to change. Both approaches are common.
List<Contact> toUpdate = new List<Contact>();
for (List<Contact> batch : [
SELECT Id, Email FROM Contact WHERE Email != null
]) {
for (Contact c : batch) {
String lower = c.Email.toLowerCase();
if (c.Email != lower) {
c.Email = lower;
toUpdate.add(c);
}
}
}
update toUpdate;This version only keeps the contacts that actually changed, so toUpdate is usually much smaller than the full result. It also issues one DML statement instead of one per chunk. It is a good fit when only a small share of rows need an update.
Avoid running a second query inside the loop body. A SOQL for loop does not make a query inside it any cheaper. A query in the body runs once per record in the single-record form, or once per chunk in the list form. It can reach the 100-query limit. Collect the Ids you need, run one query after the loop, and look the results up in a map. This is the bulk-safe pattern from the previous chapter.
Choosing between the three approaches
| Approach | Memory use | Best when |
|---|---|---|
| Assign to a `List` | Whole result in heap | The result is small and you need random access or the size |
| SOQL for loop, single record | One chunk in heap | You read or lightly process each record |
| SOQL for loop, list form | One chunk in heap | You run DML or other work per group of records |
If you need the number of rows before you start, a loop cannot tell you. Use SELECT COUNT() FROM Account WHERE ... as a separate query, or count inside the loop.
Common mistakes
- Assigning the query to a list before the loop, which loads every row at once.
- Calling DML on a single record in the single-record form, which uses up the DML statement limit.
- Assuming the loop lifts the 50,000-row limit. It does not.
- Running queries in the loop body and reaching the 100-query limit.
- Leaving out
ORDER BYwhen processing order matters.
Exercise
A method updates every Contact that matches a filter. It uses for (Contact c : [SELECT Id FROM Contact WHERE ...]) { c.Description = 'Checked'; update c; }. It fails with "Too many DML statements: 151" when the filter matches 5,000 contacts. Rewrite the loop so it uses far fewer DML statements, and say how many it will use for 5,000 records.
Show answer
Use the list form: for (List<Contact> batch : [SELECT Id FROM Contact WHERE ...]) { for (Contact c : batch) { c.Description = 'Checked'; } update batch; }. Each chunk holds up to 200 records, so 5,000 records need 25 chunks and 25 DML statements.
Exercise
A developer writes List<Account> all = [SELECT Id, Name FROM Account]; for (Account a : all) { ... } to avoid heap problems. Why does this not help, and how should it be written?
Show answer
The query is assigned to a list first, so every row is loaded into the heap before the loop begins. Put the query inside the for statement: for (Account a : [SELECT Id, Name FROM Account]) { ... }. Apex then retrieves records in chunks of 200.