Sub topic 1
The Limits That Make Large Data Hard
Prerequisites
This chapter assumes you know Apex classes, SOQL, DML, and basic Salesforce governor limits. You should also know how to run anonymous Apex in the Developer Console or an IDE.
The Limits That Make Large Data Hard
A synchronous Apex transaction runs as one unit. Salesforce applies governor limits to that unit, including limits on query rows, CPU time, heap size, and DML statements. A loop over millions of records cannot finish safely inside one transaction.
Batch Apex divides the work into smaller chunks. Each chunk runs in a separate transaction, so limits reset between chunks. This makes Batch Apex suitable for large, independent updates, cleanup jobs, and data synchronization.
What Batch Apex Is
A batch class implements Database.Batchable<SObject>. Salesforce calls three methods:
startselects or creates the records.executeprocesses one chunk.finishruns once after all chunks complete.
Feeding the Job
Use a QueryLocator when a SOQL query directly describes the records. It is the usual choice for large Salesforce tables.
Use an Iterable when records come from custom logic, several sources, or a calculated collection. An iterable gives you more control, but you must construct the records yourself and remain within applicable limits.
What Happens Inside Each Execute Call
Each execute call receives a list called scope. Salesforce commits that transaction separately. If the transaction fails, that batch rolls back without automatically rolling back successful earlier batches.
public class AccountRatingBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
[SELECT Id, Rating FROM Account WHERE Rating = null]
);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account accountRecord : scope) {
accountRecord.Rating = 'Cold';
}
update scope;
}
public void finish(Database.BatchableContext bc) {
System.debug('Batch complete: ' + bc.getJobId());
}
}The next chapter covers how to start this class, choose its batch size, and monitor the queued job.
Exercise
Why can a batch job process more records than one synchronous transaction?
Show answer
Each execute call runs in a separate transaction, so governor limits reset for every chunk.