In this blog series, we delve into 20 real-world Batch Apex scenario-based interview questions that commonly arise in Salesforce development interviews, providing you with the knowledge and skills to tackle them confidently.
Firstly, we will go through the concepts of batch apex and the methods we used in batch apex and syntax.
What is Batch Apex?
The Batch class executes every transaction, by breaking down large sets of data into small chunks and providing us with the additional benefit of a governor limit.
It provides us with a higher SOQL query limit. It implements a Database.Batchable interface.
Database.Batchable Interface has three methods that we have to implement:
- Start – We collected the records either with a Database.QueryLocator or Iterable to pass them in the execute.
- Execute – We performed the logic on the collected data. It will run multiple times according to the batch size.
- Finish – We can do any post activities like sending emails.
Syntax:
To learn more about Batch Apex in Salesforce click here
Let’s move forward with batch apex scenario-based interview questions.
Question 1. Why do we use a batch class when we have other tools, such as a data loader, for operating on bulk data?
Answer – Yes, we can use a data loader if and only if we have to perform operations statically or that can be done through Excel. However, batch processing comes into the picture when we require more customization, complex logic, or any calculations at runtime that can’t be done through Excel.
For example, we can query data in the start method according to some filter criteria or any related queries.
Question 2. What is the default and maximum size of the batch?
Answer – The default is 200 and the maximum size is 2000.
Question 3. What are the methods essential for writing the batch class?
Answer – For writing batch class we first need to implement Database.Batchable and then we need to define three methods of this interface which are
- Start
- Execute
- Finish
Question 4. Can we call batch class from another batch class?
Answer – Yes, we can call another batch class from a batch class in the finish method.
Below is a sample code snippet demonstrating how we can call a batch from another batch. Specifically, we are invoking the BatchChainingDemo class from UpdateContactFields.
Syntax
BatchChainingDemo.apxc
UpdateContactFields.apxc
Note: Hence, if we try to call the batch from Start or Execute we will get the below error.
Question 5. How can we schedule batch classes?
Answer – We can schedule the batch apex by using System.scheduleBatch
Example:
Here, ‘batchObj‘ represents the instance, ‘schedule batch example‘ denotes the job name, and ’60’ signifies the duration in minutes, indicating that the batch will be executed 60 minutes from now.
Also, it will return the Job ID that we can use to monitor, abort, etc. our Batch Job.
Question 6. Business Scenario:
Let’s say I have a batch with a total of 1000 records to execute, and the batch size is set to 200. This means that the processing will occur in 5 batches. If the first 4 batches are processed successfully but encounter an error in the 5th batch due to 4-5 records, the question is whether the entire batch is rolled back or only those 4-5 problematic records are rolled back.
Answer – In this scenario, that entire batch is rolled back.
Answer – We can handle this scenario by utilizing the Database method available. Additionally, below is a sample of how we can address any errors encountered by a batch.
Question 8. Can we call the future from batch class?
Answer – No, we cannot call future methods from batch apex. As they operate differently. Mixing these can lead to unexpected behaviour.
Question 9. How to make callouts from batch classes?
Answer – To make callouts using batch class we need to implement Database.AllowsCallouts interface.
Syntax
Question 10. How many records can be retrieved via Database.QueryLocator?
Answer – We can retrieve 50 Million records by using Database.QueryLocator.
Question 11. How do you track the status of the batch class?
Answer – When we execute the batch we get the job ID by which we can track the status of the batch class. There are two ways by which we can track the status
- From UI Apex Job – Navigate to setup –> Quick Find Box –> Search for Apex Job
- Query on AsyncApexJob
Example: AsyncApexJob aaj = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob WHERE ID =: batchprocessid ];
Question 12. Is it possible to reorder the batch class?
Answer – Batch class executes based on “first-in, first-out” in the order they have submitted. If we want to reorder the batch to make it process the first whenever the resources get available, we can do that in two ways:
- From UI Apex Flex Queue – Batch Jobs that are in holding status go into the flex queue. To navigate to the Apex Flex queue, go to setup –> Quick Find box –> Apex Flex Queue
- By using System.FlexQueue methods
Syntax
Question 13. Business Scenario:
Let’s suppose you have a batch that is running on 1000 records with 200 as a batch size so it will run 5 times. Now the requirement is user wants to have total success records and total failed records to mail with the specified mail address. How can we execute this?
Ansewer – We can perform this operation by implementing a Database.Stateful interface. By using this our instance variable will maintain the state across multiple batches. Normally, when a batch job runs (without implementing Database.Stateful ) the instance variable gets reset between batch executions.
Syntax
Question 14. How can I abort my Batch Job?
Answer – To abort the Batch Job we have to use the following syntax
Note: Hence, batch Job that has already started can’t be aborted. Only batch jobs that are in status Queued and holding can be aborted.
Question 15. What happens if an unhandled exception occurs in the execute method of a Batch Apex class?
Answer – If errors are not handled properly in the Batch Job, and the execute method encounters some exceptions, then the job gets terminated. Consequently, we have to handle errors properly in the Batch Job.
For example: we can use a Database.Stateful interface to capture errors.
Question 16. How to publish platform events in the execution of batch jobs?
Answer – To fire a platform we have to implement a Database.RaisesPlatformEvents in our batch class.
Question 17. What is the difference between Database.QueryLocator and Iterable?
Answer – Major difference between Database.QueryLocator and Iterable is that with queryLocator the governor limit for the total number of records retrieved by SOQL queries is bypassed and you can query up to 50 million records. However, with an Iterable, the governor limit for the total number of records retrieved by SOQL queries is still enforced.
Also, with Iterable we can perform some custom logic and then we can pass it to execute but with queryLocator, it is simple SOQL. So If you want to perform some logic to filter your data that can’t be possible with queryLocator use Iterable. In most of the cases, it can be achieved by queryLocator.
Question 18. Can we call batch class from the trigger?
Answer – While we can call a batch class from the trigger, it is not advisable to do so. However, if we have to call it, we need to follow some considerations: Ensure that we do not call batch apex from the trigger each time. This is because of the reason that we can only have 5 apex jobs queued or executed at a time. Additionally, it should be bulkified to handle large columns of data
Question 19. How would you ensure that Batch Apex processes records efficiently and doesn’t hit governor limits?
Answer – Although the batch is used to avoid hitting the governor limit still there can be a chance that we might hit it.
The following things can be ensured to avoid hitting those limits:
- Code optimization
- DML withing loops
- Process records in smaller batches
Question 20. Business Scenario:
Write a Batch Apex class to update the “OpportunityStage” field of all Opportunity records based on their “CloseDate”.
Answer – Below is the syntax to achieve the given scenarios
Conclusion
In this blog, we’ve explored a range of scenario-based interview questions focused on Batch Apex, a powerful tool for processing large volumes of data in Salesforce. Through these scenarios, we’ve covered various aspects of Batch Apex, including its implementation, error handling, governor limits, performance optimization, and integration with other Salesforce features.
Best of luck with your interview preparations !!
This asset is incredible. The radiant material shows the maker’s earnestness. I’m dumbfounded and envision more such astonishing presents.
Question 4. Can we call batch class from another batch class?
Answer – Yes, we can call another batch class from a batch class in the finish method.
But an Example, it shows an Execute method. is it correct…?