SOQL For Loops
By the end of this lesson, you'll be able to:
- Loop directly over a SOQL query without storing the full result in a List first
- Explain how a SOQL for loop processes records in batches internally
- Recognize when this pattern matters for very large result sets
Prerequisites: "Aggregate Functions and GROUP BY"
The familiar way vs the SOQL for loop
// Familiar: query first, then loop
List<Account> accounts = [SELECT Id, Name FROM Account];
for (Account acc : accounts) {
System.debug(acc.Name);
}
// SOQL for loop: query and loop combined
for (Account acc : [SELECT Id, Name FROM Account]) {
System.debug(acc.Name);
}
Both loops visit the same records in the same order — the difference is entirely in how the records are fetched and held in memory, covered next.
Why this matters at scale
Assigning a query straight to a List<Account> loads every matching record into memory all at once — for tens of thousands of records, this risks hitting Apex's heap size limit. A SOQL for loop instead fetches records in internal batches of 200 behind the scenes, processing each batch before fetching the next, keeping memory use low regardless of how many total records match.
When to reach for this pattern
For typical queries — dozens or a few hundred records — either style works fine, and the plain List version is often more readable since the data can be inspected or reused after the loop. Reach for the SOQL for loop specifically when a query might realistically return thousands of records, most commonly inside Batch Apex (a later Asynchronous Apex module), which is purpose-built around this exact pattern.
Exercise
Rewrite this List-based loop as a SOQL for loop.
Show hint
for (Contact con : [SELECT Id, LastName FROM Contact]) { ... }
SOQL For Loops Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A SOQL for loop iterates directly over a query's results without ever holding the entire result set in memory at once — the safest way to process a genuinely large number of records.