Batch Apex in Salesforce

What is Batch Apex? It allows you to define a job that can be divided into manageable chunks, where each chunk can be processed separately.

For example, if you want to make a field update of all records in any object which is having more number of records, then governor limits restricts us to process that operation. Because in a single transaction we can only process 10,000 records.

In batch apex, it will fetch all records which you want to perform the field update and divide them into a list of 200 records & every 200 records operation is performed separately.

What is Batchable Interface? To use Batch Apex, you must implement “Database.Batchable”. This interface has three methods. those are:

  1. Start
  2. Execute
  3. Finish

Start method is automatically called at the beginning of the apex job. This method will collect record or objects on which the operation should be performed. These records are divided into subtasks and pass those to execute method.

Execute Method performs an operation which we want to perform on the records fetched from start method.

Finish method executes after all batches are processed. Use this method to send confirmation email notifications.

To understand this see the below class. Below program updates Account name in the account object with “*****” after the account name.

global class batchAccountUpdate implements Database.Batchable<sObject> {
	
	global Database.QueryLocator start(Database.BatchableContext BC) {
		String query = 'SELECT Id,Name FROM Account';
		return Database.getQueryLocator(query);
	}
	
	global void execute(Database.BatchableContext BC, List<Account> scope) {
		for(Account a : scope) {
			a.Name = a.Name + '******';
		}
		update scope;
	}
	
	global void finish(Database.BatchableContext BC) {
	}
}