Sub topic 4
Feeding the job: QueryLocator or Iterable
This chapter assumes you can write Apex classes and SOQL, and that you know the basic shape of a batch class: start, execute and finish. Here we look closely at start, the method that decides which records the job processes and how they reach execute.
What start has to return
The start method runs once, at the beginning of the job. It returns one of two types:
Database.QueryLocator, created withDatabase.getQueryLocator.Iterable<T>, whereTis the type your class passes toDatabase.Batchable<T>.
Both give the platform a source of records. The platform slices that source into chunks, and each chunk becomes the scope list for one execute call. The difference is in where the records come from and which limits apply while they are collected.
QueryLocator
A QueryLocator hands the platform a SOQL query and lets the platform run it. The records are not loaded into your start method's heap. The platform reads them chunk by chunk as the job runs. Because of that, the usual 50,000-row limit on SOQL rows does not apply to the query. A QueryLocator can cover up to 50 million records.
public class StaleLeadBatch implements Database.Batchable<SObject> {
private final String query;
public StaleLeadBatch(Integer daysOld) {
query = 'SELECT Id, Status FROM Lead '
+ 'WHERE LastModifiedDate < LAST_N_DAYS:' + daysOld
+ ' AND IsConverted = false';
}
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(query);
}
public void execute(Database.BatchableContext bc, List<Lead> scope) {
for (Lead l : scope) {
l.Status = 'Unresponsive';
}
update scope;
}
public void finish(Database.BatchableContext bc) {}
}Points to know about this approach:
Database.getQueryLocatoraccepts either a static query in square brackets or a dynamic query string. Use the string form when the filter depends on constructor arguments, as above.- Build dynamic strings carefully. If any part comes from user input, escape it with
String.escapeSingleQuotesor use bind variables, which the locator resolves from variables visible whengetQueryLocatoris called. Integers likedaysOldare safe to concatenate. - The query runs when
startruns. Records created after that point are not part of this job. - The scope type follows the SObject type in the query. The
executesignature can declareList<Lead>instead ofList<SObject>, which saves you casting. - Only the fields you select are available in
execute. Reading an unselected field throws aSystem.SObjectException.
Iterable
An Iterable lets your own code decide what gets processed. Use it when the records cannot be expressed as one SOQL query. Typical cases are:
- Aggregate queries with
GROUP BY, which a QueryLocator does not support. - Data assembled from several queries or objects.
- Custom Apex types, such as wrapper classes or values parsed from a file or an API response.
The cost is that your code builds the collection inside start. Any SOQL you run there counts against the normal limits for that transaction, including the 50,000-row limit and the heap size limit. An Iterable does not let you scale to millions of rows by itself. It lets you process a prepared collection in separate transactions.
The example below groups opportunities by account and writes each total back to the account. The first class wraps a list as an Iterable.
public class RowIterable implements Iterable<AggregateResult> {
private final List<AggregateResult> rows;
public RowIterable(List<AggregateResult> rows) {
this.rows = rows;
}
public Iterator<AggregateResult> iterator() {
return rows.iterator();
}
}The batch class then returns it from start. Its type parameter is AggregateResult, so execute receives a List<AggregateResult>.
public class OpportunityTotalsBatch implements Database.Batchable<AggregateResult> {
public Iterable<AggregateResult> start(Database.BatchableContext bc) {
return new RowIterable([
SELECT AccountId acct, SUM(Amount) total
FROM Opportunity
WHERE AccountId != null AND IsWon = true
GROUP BY AccountId
]);
}
public void execute(Database.BatchableContext bc, List<AggregateResult> scope) {
List<Account> toUpdate = new List<Account>();
for (AggregateResult ar : scope) {
toUpdate.add(new Account(
Id = (Id) ar.get('acct'),
AnnualRevenue = (Decimal) ar.get('total')
));
}
update toUpdate;
}
public void finish(Database.BatchableContext bc) {}
}Start it the usual way, with Database.executeBatch(new OpportunityTotalsBatch(), 200);. If the aggregate query returns more than 50,000 groups, start fails with a query row limit error. Filter the query, or move to a different design (see below).
Comparing the two
| Aspect | QueryLocator | Iterable |
|---|---|---|
| Who runs the query | The platform | Your code in `start` |
| Row ceiling | 50 million | Normal SOQL limits in `start` (50,000 rows), plus heap |
| Element type | SObject | SObject or any Apex type |
| Aggregate (`GROUP BY`) queries | Not supported | Supported |
| Multiple sources | One query | Anything you can assemble |
| Memory use | Records are read per chunk | Whole collection held in memory |
| Default choice | Yes | When a single query cannot express the input |
Edge cases
- Large Iterable collections. If you build a list of 200,000 wrappers in
start, that list sits in heap for the wholestarttransaction. Keep elements small, such as Ids, and re-query the full records inexecute. - Ids instead of records. A common pattern is to return a lightweight collection from
startand query insideexecutewithWHERE Id IN :ids. That gives you fresh field values at processing time, at the cost of one query per chunk. - Empty input. If the query or collection is empty,
executenever runs.finishstill runs, so do not assumeexecutehappened. - Locking. A QueryLocator query cannot use
FOR UPDATE. If you need to lock rows, do it inexecutewith a second query on the chunk's Ids. - Sort order. Without an
ORDER BY, the order of records is not guaranteed. If your logic depends on order across chunks, state it in the query. - Changing data. Records can change between the start of the job and the processing of their chunk. Check in
executethat a record still meets your criteria before you change it. That also makes the job safe to re-run.
Choosing in practice
- Can one SOQL statement without
GROUP BYselect all the records? Use a QueryLocator. - Do you need aggregates, a join across unrelated objects, or non-SObject data? Use an Iterable.
- Will the Iterable's collection stay well under the 50,000-row and heap limits? If not, redesign so a QueryLocator can drive the job. For example, put the grouping key on a field and process by that field.
Exercise
A batch job must process 8 million Contact records where Email is blank. A teammate suggests building a List<Contact> in start and returning it as an Iterable. Which return type should you use, and why?
Show answer
Use a QueryLocator with Database.getQueryLocator('SELECT Id FROM Contact WHERE Email = null') or a static query. The platform reads the rows chunk by chunk, so the 50,000-row SOQL limit does not apply and the query can cover up to 50 million rows. Building a list in start would hit the row limit and the heap limit before the first execute call.
Exercise
You need a job that sums Amount by AccountId using GROUP BY and writes the total to each account. Why can't you use a QueryLocator, and what do you return from start instead?
Show answer
A QueryLocator does not support aggregate queries. Declare the class as Database.Batchable<AggregateResult>, run the aggregate query inside start, and return it wrapped in an Iterable<AggregateResult>, as RowIterable does above. The aggregate query counts toward the normal limits in start, so it must return fewer than 50,000 groups.