When should you choose Database.getQueryLocator() over an iterable in Batch Apex?
Answer
Basics: Batch Apex start() must return either a QueryLocator or an Iterable. A QueryLocator is a server-side cursor: Salesforce holds the query and feeds chunks to execute(), so your code never loads the whole set into memory.
How it works:
start()returnsDatabase.getQueryLocator('SELECT ...').- The platform opens the cursor and slices the results into scopes (default 200).
- Each scope runs in its own
execute()transaction with fresh limits. finish()runs at the end.
Advanced / deep dive: With a QueryLocator the total rows retrieved are not counted against the 50,000 row limit (the 50 million cap applies). With an Iterable, start() is an ordinary transaction, so the 50,000 SOQL row limit and heap limits apply to whatever you build there. Limitations of QueryLocator: no aggregate queries (GROUP BY), the query must be a SOQL SObject query, and you cannot combine data from callouts or computed collections. Use Database.getQueryLocatorWithBinds for safe, explicit bind variables rather than string concatenation (injection risk). If you need filtering that SOQL cannot express, prefer to filter in execute() rather than switch to an Iterable.
Code / config example:
public class OldCaseCloser implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
Map<String,Object> binds = new Map<String,Object>{
'cutoff' => Date.today().addDays(-90)
};
return Database.getQueryLocatorWithBinds(
'SELECT Id, Status FROM Case WHERE CreatedDate < :cutoff AND IsClosed = false',
binds, AccessLevel.USER_MODE);
}
public void execute(Database.BatchableContext bc, List<Case> scope) {
for (Case c : scope) { c.Status = 'Closed'; }
update scope;
}
public void finish(Database.BatchableContext bc) {}
}
Hidden gotchas & must-remember points:
- 50 million records for QueryLocator; 50,000 for rows queried in an Iterable
start(). - Aggregate queries fail with a QueryLocator.
- Records are queried at start, but
execute()receives the data as it was when the cursor read it; concurrent edits can make it stale. - Add selective filters and indexed fields to avoid query timeouts on huge tables.
- Default scope is 200, max 2000.
- Dynamic strings need
String.escapeSingleQuotesor bind variables.
Best practice: Default to QueryLocator; reach for an Iterable only when the source is not SOQL.