Batch Classes
What is Batch Apex?
Batch Apex is used when you need to process a large number of records (more than 50,000) in Salesforce without hitting governor limits.
Salesforce breaks your job into small chunks (called batches) and processes them one at a time in the background.
Why Use Batch Apex?
You should use Batch Apex when:
• You need to update/delete a large number of records (more than 50,000).
• You want to automate tasks like data cleanup, mass updates, etc.
• You want to run something in the background (asynchronously).
Basic Structure of a Batch Class
To create a batch class, you must implement the Database.Batchable<SObject> interface.
It contains 3 required methods:
apex
global class YourBatchClass implements Database.Batchable<SObject>
{ // Step 1: Start Method – Select Records to Process
global Database.QueryLocator start(Database.BatchableContext bc) {
// Return the records using SOQL }
// Step 2: Execute Method – Process Each Batch
global void execute(Database.BatchableContext bc, List<SObject> scope)
{ // Your logic for updating/deleting records
}
// Step 3: Finish Method – Run After All Batches Complete
global void finish(Database.BatchableContext bc) {
// Optional final actions (e.g., send email or log) } }
Example: Update Contact Descriptions
Business Requirement:
Update all Contact records and set their Description field to:
“Updated by Batch“
apex
global class ContactBatchUpdate implements Database.Batchable<SObject> {
global Database.QueryLocator start(Database.BatchableContext bc) {
// Select all Contacts
return Database.getQueryLocator(‘SELECT Id, Description FROM Contact’);
}
global void execute(Database.BatchableContext bc, List<SObject> scope) {
// Update description for each contact in this batch
for(SObject s : scope) {
Contact c = (Contact)s;
c.Description = ‘Updated by Batch’;
}
// Save updated records
update scope;
}
global void finish(Database.BatchableContext bc) {
System.debug(‘Batch process completed!’);
}
}
How to Run It:
Run this in Anonymous Window:
apex
ContactBatchUpdate batch = new ContactBatchUpdate();
Database.executeBatch(batch, 200); // 200 = batch size
Code Explanation:
Method | Purpose |
---|---|
start() | Runs first. It selects all Contact records from the database. |
execute() | Runs for each batch. It updates each Contact’s Description. |
finish() | Runs at the end. It logs a message saying batch is complete. |
Output:
All Contact records in your org will have this in the Description field:
“Updated by Batch”