Sub topic 2
Starting a Job with `Database.executeBatch`
Assume you know Apex classes, SOQL, DML, and Salesforce governor limits. Batch Apex runs large data work in separate transactions. Each transaction processes one scope of records, so limits reset between scopes.
Starting the job
Call Database.executeBatch with a batch class instance and an optional scope size. The method queues the job and returns an asynchronous job ID.
Id jobId = Database.executeBatch(new AccountRatingBatch(), 200);
System.debug('Started batch job ' + jobId);The scope size controls how many records Salesforce passes to each execute call. The default is 200. A smaller scope helps when each record uses many queries, DML statements, or complex processing. A larger scope can reduce overhead when processing is simple.
Sharing state across batches
Each execute call has a separate transaction. Instance fields normally do not retain values between those calls. Add Database.Stateful when you need counters or other small state to survive.
public class AccountRatingBatch
implements Database.Batchable<SObject>, Database.Stateful {
public Integer succeeded = 0;
public Integer failed = 0;
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 account : scope) {
account.Rating = 'Cold';
}
List<Database.SaveResult> results = Database.update(scope, false);
for (Database.SaveResult result : results) {
if (result.isSuccess()) {
succeeded++;
} else {
failed++;
for (Database.Error error : result.getErrors()) {
System.debug(error.getMessage());
}
}
}
}
public void finish(Database.BatchableContext bc) {
System.debug('Succeeded: ' + succeeded + ', failed: ' + failed);
}
}Database.update(scope, false) enables partial success. Valid records are saved even when another record fails. Inspect each SaveResult and log or persist the errors.
Exercise
Why might you choose a scope size of 50 instead of 200?
Show answer
Choose 50 when each record needs substantial queries, DML, or processing and a scope of 200 risks hitting governor limits.