The start method of a batch class can return one of two things: a Database.QueryLocator or an Iterable. Use Database.getQueryLocator when the records come from one SOQL query. It can process up to 50 million records, and the SOQL row limit doesn't apply to it. Use an Iterable when the data doesn't come from a single plain query: aggregate results, records built from several queries, data from a callout, or rows you filter with logic you can't write in SOQL. The catch is that the normal 50,000-row SOQL limit still applies to whatever you query in start.
Below: both versions side by side, the limits, when I pick each, and the mistakes that cause most batch failures.
Quick comparison
Database.QueryLocator | Iterable | |
|---|---|---|
| Where the data comes from | One SOQL query | Anything: a list, several queries, an aggregate query, a callout |
| Maximum records | 50 million | Limited by governor limits (50,000 SOQL rows) |
Aggregate queries (GROUP BY, COUNT) | Not supported | Supported |
| Custom filtering logic | Only what SOQL can express | Any Apex logic |
| Typical use | Large data clean-ups, recalculations, nightly jobs | Small to medium jobs with unusual input |
If you're not sure, start with getQueryLocator. Most batch jobs are "query these records and process them in chunks", which is exactly what it's built for.
Batch Apex with Database.getQueryLocator
public with sharing class DeactivateStaleContactsBatch implements Database.Batchable<sObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
Date cutoff = Date.today().addYears(-3);
return Database.getQueryLocator([
SELECT Id, Active__c
FROM Contact
WHERE LastActivityDate < :cutoff AND Active__c = true
]);
}
public void execute(Database.BatchableContext bc, List<Contact> scope) {
for (Contact c : scope) {
c.Active__c = false;
}
update scope;
}
public void finish(Database.BatchableContext bc) {
System.debug('Stale contacts deactivated.');
}
}
Run it with:
Database.executeBatch(new DeactivateStaleContactsBatch(), 200);
What happens behind the scenes: Salesforce runs the query once in start, keeps a server-side cursor, and hands execute one chunk at a time (200 records by default, up to 2,000). Each execute call is its own transaction with its own governor limits. That's why one batch can work through millions of records.
Dynamic queries: getQueryLocator with a String, or with binds
When the query is built at runtime, pass a String:
String soql = 'SELECT Id FROM Account WHERE Industry = \'' + String.escapeSingleQuotes(industry) + '\'';
return Database.getQueryLocator(soql);
Concatenating values is easy to get wrong, so I prefer Database.getQueryLocatorWithBinds. You pass the variables in a map, and you can choose the access level too:
public Database.QueryLocator start(Database.BatchableContext bc) {
Map<String, Object> binds = new Map<String, Object>{ 'industry' => this.industry };
return Database.getQueryLocatorWithBinds(
'SELECT Id, Name FROM Account WHERE Industry = :industry',
binds,
AccessLevel.USER_MODE
);
}
AccessLevel.USER_MODE enforces the running user's object and field permissions and sharing on the query. Use SYSTEM_MODE only when the job really must see everything, and say why in a comment.
Batch Apex with an Iterable
Here's a case getQueryLocator can't handle: you need one row per account with a count of open cases, which means an aggregate query.
public with sharing class FlagBusyAccountsBatch implements Database.Batchable<AggregateResult> {
public Iterable<AggregateResult> start(Database.BatchableContext bc) {
return [
SELECT AccountId, COUNT(Id) openCases
FROM Case
WHERE IsClosed = false AND AccountId != null
GROUP BY AccountId
HAVING COUNT(Id) > 10
];
}
public void execute(Database.BatchableContext bc, List<AggregateResult> scope) {
List<Account> updates = new List<Account>();
for (AggregateResult row : scope) {
updates.add(new Account(
Id = (Id) row.get('AccountId'),
Open_Case_Count__c = (Integer) row.get('openCases')
));
}
update updates;
}
public void finish(Database.BatchableContext bc) {}
}
Two things to notice:
- The class implements
Database.Batchable<AggregateResult>, notDatabase.Batchable<sObject>. The type parameter matches whatstartreturns. startreturns a List. A List implementsIterable, so you don't need to write your own iterator class for most jobs.
You only need a custom class that implements Iterable and Iterator when the items are produced lazily, for example when paging through an external API. That's rare in practice.
The limit that catches people
With an Iterable, the rows you query in start count against the normal limit of 50,000 SOQL rows per transaction. If the query in start returns 50,001 records, the job fails before execute ever runs, with System.LimitException: Too many query rows: 50001.
So an Iterable is fine for "a few thousand aggregated rows". It's the wrong tool for "every Contact in a big org". When the volume can grow, move the logic into execute and drive the job with a QueryLocator instead.
Which one I pick
- Records come from one SOQL query โ
getQueryLocator. Even for small volumes, because the job keeps working when the data grows. - You need
GROUP BYorCOUNTโ Iterable over the aggregate results. - Records come from two or more queries that you merge โ Iterable, if the total stays well under 50,000 rows. Otherwise, query one object with a QueryLocator and do the second query inside
executefor just that chunk. - Data comes from a callout โ Iterable. Add
Database.AllowsCalloutsto the class. - Filtering needs logic SOQL can't express โ Usually still a QueryLocator. Query a superset and skip the records you don't want inside
execute. That keeps the 50 million record headroom.
Mistakes that cause most batch failures
- Returning a List from a method declared to return
Database.QueryLocator. It won't compile. Change the return type toIterable<sObject>, or wrap the query inDatabase.getQueryLocator(...). - Using an aggregate query inside
getQueryLocator. Not supported. Use an Iterable. - Querying a huge object with an Iterable. You hit the 50,000-row limit in
start. Switch to a QueryLocator. - Doing SOQL or DML for each record in
execute. Each chunk has the normal limits of 100 queries and 150 DML statements. Bulkifyexecutelike you would a trigger. - Using
getQueryLocatoroutside Batch Apex and expecting 50 million. Outside a batchstart, a QueryLocator is limited to 10,000 records.
For more on chunk sizes, Database.Stateful and error handling, read best practices for Batch Apex. For the full set of limits that apply in execute, see governor limits in Salesforce.
Learn it by building it
Every course, every code repository, the discussion group and certificates of completion โ one subscription.
Frequently asked questions
How many records can Database.getQueryLocator return in Batch Apex?
Up to 50 million records when it's returned from the start method of a batch class. Outside Batch Apex, for example in a StandardSetController, a QueryLocator is limited to 10,000 records.
What is the record limit when start returns an Iterable?
The normal governor limit for SOQL rows applies, so any query you run in start can retrieve at most 50,000 records in total. That is why Iterable is the wrong choice for very large data volumes.
Can I use an aggregate query with Database.getQueryLocator?
No. Aggregate queries with GROUP BY or COUNT aren't supported in a QueryLocator. Run the aggregate query in start and return the results as an Iterable instead.
Can I return a List from the start method?
Yes. A List implements Iterable, so a start method declared to return Iterable<Account> can simply return a List<Account>. The 50,000-row SOQL limit still applies.
Keep going
Blog
Understanding Batch Apex easily
Blog
What are the Best practices to follow in Batch Apex?
Blog
Governor Limits in Salesforce: What They Are and How to Stay Under Them
Topic guide
Learn Apex: A Hands-On Salesforce Apex Course for Developers
Blog
Apex Bulkification: Fix 'Too Many SOQL Queries: 101'
Blog
Apex Test Classes: Stop Chasing 75% Coverage