Salesforce uses governor limits to ensure efficient resources in a multi-tenant environment. Asynchronous apex helps handle the governor limits in a multi-tenant architecture. We have batch Apex types in asynchronous processes in Salesforce Apex.
In this tutorial, we will learn about Batch Apex in Salesforce, using examples. In that, I will explain what Batch Apex is in Salesforce, its methods, and how to use a Batch Apex in Salesforce.
What is Batch Apex in Salesforce?
The batch class executes every transaction by breaking down large datasets into small blocks or batches, providing us with the additional benefit of a governor limit.
Every batch in the batch apex runs with the new set of governor limits. In other words, the governor limit will reset for every executing batch.
The batch apex implements the Database.Batchable interface provides enhanced control over record processing compared to the standard synchronous Apex.
How to Use Batch Apex in Salesforce?
To use batch Apex, we must implement the Salesforce-provided interface Database.Batchable.
To monitor the batch Job, we can go to Apex Jobs in the Quick Find box in the setup. There, we can monitor our jobs or stop their execution. Database.Batchable Interface has three methods that we have to implement
Important Methods of Batch Apex in Salesforce
The following are three important methods in batch apex in Salesforce.
Start() Method in Batch Apex:
In the start() method of batch apex, we collect the records of objects with a Database.QueryLocator and pass them into the execute method for the operation.
Syntax of Start() Method:
public Database.QueryLocator start( Database.BatchableContext BC ){ }Database.QueryLocator is used in batch Apex to retrieve records. This bypasses the usual governor limit of 50,000 records for SOQL queries.
Execute() Method in Batch Apex:
The start method collects data and passes it to the execute() method, which breaks it into batches. This method runs multiple times according to the provided batch size.
Syntax of Execute() Method:
public void execute( Database.BatchableContext BC, list<P>){ }It takes an additional parameter, which will be the list collection of object records that we have collected in the start method.
Finish() Method in Batch Apex:
This method will run after processing all the batches, and it is also optional. However, we can use it to perform any post-processing activities, such as displaying a success message, sending email notifications, logging batch completion, and triggering another batch job.
Syntax of Finish() Method:
public void finish( Database.BatchableContext BC ){ }Example: Create a Batch Apex in Salesforce
Now, I will explain how to create a batch Apex by implementing the Database.Batchable interface and how to execute it in Salesforce with step-by-step instructions.
For example, If any account is not active (Active__c checkbox field), then in the description field of all related contacts, update as ‘ This contact’s account is not active,’
We created this batch apex to update contact records that meet certain criteria by setting their Description field to ‘This contact’s account is not active.’
Now, let’s create the batch Apex class, and then I will explain step by step how we implemented it.
public class UpdateContacts implements Database.Batchable<sObject> {
public String query;
public UpdateContacts(String query) {
this.query = query;
}
public Database.QueryLocator start( Database.BatchableContext BC ){
return Database.getQueryLocator( query );
}
public void execute(Database.BatchableContext BC, List<sObject> records){
List<Contact> contacts = new List<Contact>();
for(sObject sObj : records)
{
Contact con = (Contact)sObj;
con.Description = 'This contact's account is not active';
contacts.add(con);
}
update contacts;
}
public void finish(Database.BatchableContext BC)
{
system.debug('All contacts description has been updated which accounts are deactvate');
}
}We created an Apex class, UpdateContacts, which implements the Database.Batchable<sObject> interface allows processing large volumes of records asynchronously in batches.
After that, we created a constructor and passed a string variable to it.
After class declaration, we declare a string variable named query. Then, the start() method executes only once and returns a Database.QueryLocator, which defines the scope of records to process. After that, pass the query string, which determines which contacts will be processed.
After that, we have the execute() method, which processes a batch of records at a time, and the records parameter contains a subset of records(contacts object). Then, we created a list collection to store the records that would be updated.
The for loop iterates through the records and casts each sObject. Then, the (Contact)s performs typecasting, converting the generic sObject into a Contact object. This allows us to access Contact-specific fields, such as Description.
After that, update the description field, and all modified contact records are updated in Salesforce using the updated contacts.
The finish() method executes after all batches are completed, and there, we display a completion message.
Before Executing the Batch Class, Check the Image Below:
Here, we have the account record, and in the active field, you can see that there is a ‘No’ value. That means this account is not active. Now, we need to update the description field of contacts related to this account.

In the related contact, you can see that the description field is empty.

How to Execute Batch Apex?
To execute the batch apex, open an anonymous window, and first, we have to create an instance of our batch class. Then, pass the query to the constructor to retrieve the contacts whose related accounts are not active.
After that, we used the instance of a class called the executeBatch method, where we updated the related contact’s description field.
UpdateContacts batchObj = new UpdateContacts( 'SELECT Id, Name,
Account.Active__c FROM Contact WHERE Account.Active__c = \'No\' ' );
Database.executeBatch( batchObj );After that, click the Execute button to run the Apex code.
Output:
After executing the batch apex class, the debug statement we added will be displayed in the debug log. There, we provided a message in the finish() method.

Then, as you navigate to the contacts whose accounts are not active, the description is updated to the message that we provided.

Check the Apex Job in the Salesforce Org
We can also check the status of the batch class in apex Job in the Quick Find box from setup. Hence, this batch job gets executed successfully, and the status is updated to Completed.

In this way, we can use batch apex class to handle the governor limits in a multi-tenant architecture in Salesforce if we have a number of records that will exceed governor limits.
Conclusion
I hope you have got an idea about the batch apex in Salesforce with examples. In that, I have explained what batch apex is in Salesforce, their methods, and how to use a batch apex in Salesforce.
You may like to read:
- Queueable Apex Chaining in Salesforce With Examples
- Scheduler Apex in Salesforce With Examples
- Inheritance in Salesforce Apex
- Polymorphism in Salesforce Apex
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.