How to Write a Batch Apex in Salesforce

In this post, let us learn about the Batch Apex and its usage. Once after completing this post, you will be able to write a batch class very comfortably.

When to go for Batch Apex?

As a developer, we may come across situations to handle thousands of records for a database operation. In those cases, batch apex simplifies our processing time and system complexity. Batch apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks.

These jobs can be programmatically invoked at runtime using apex. We can have only 5 queued or active batch jobs at one time.

How to use Batch apex?

Write an apex class – by implementing the interface Database.Batchable and then invoke the class programmatically.

Database.Batchable – Contains 3 methods


return type: Iterable |Querylocatorarguments : Database.batchableContextexecute()

no return typearguments : Database.batchableContext , List<Sobject> scopefinish()

no return typearguments : Database.batchableContextExample: Use Case: Reassign Account owner

global class OwnerReassignment implements Database.Batchable<sObject> {
	String query;
	String email;
	Id toUserId;
	Id fromUserId;
	global Database.querylocator start(Database.BatchableContext BC) {
		return Database.getQueryLocator(query);
	global void execute(Database.BatchableContext BC, List<sObject> scope) {
		List<Account> accns = new List<Account>();
		for(sObject s : scope){Account a = (Account)s;
		if(a.OwnerId==fromUserId) {
	update accns;}global void finish(Database.BatchableContext BC) {
		Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
		mail.setToAddresses(new String[] {email});
		mail.setReplyTo('[email protected]');
		mail.setSenderDisplayName('Batch Processing');
		mail.setSubject('Batch Process Completed');
		mail.setPlainTextBody('Batch Process has completed');
		Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

The above code can be run by executing the below snippet from Anonymous window

OwnerReassignment reassign = new OwnerReassignment();
reassign.query = 'SELECT Id, Name, Ownerid FROM Account ' + 'WHERE ownerid=\"' + + '\"'; = '[email protected]';
reassign.fromUserId = u;
reassign.toUserId = u2;
ID batchprocessid = Database.executeBatch(reassign);

References: Salesforce apex developer guide

Popular Salesforce Blogs