Salesforce Batch Apex Interview Questions & Answers

2. Explain methods used in batch Apex?

Start: This method is called at the starting of a batch job to collect the data on which the batch job will be operating. It breaks the data or record into batches.

Execute: This method executes after the Start method, and it does the actual processing for each batch, separately.

global void execute(Database.BatchableContext BC, list<sobject>) {}

Finish: This method will be called at last. Since this method is called in the end, it is responsible to perform post-processing operations such as sending an email. When this process is called all batches are already executed.

global void finish(Database.BatchableContext BC) {}
3. How to Invoke a Batch Class?
Database.executeBatch(new BatchApexExample(),100);
4. How to Monitor Batch Apex?

To monitor or stop the execution of the batch Apex job, from Setup, enter Apex Jobs in the Quick Find box, then select Apex Jobs.

5. Explain Chaining in Batch Apex?

At maximum, only 5 Batch jobs can be chained to one another.

global database.querylocator start(Database.BatchableContext BC)
{
    //start method logic here
}
global void execute(Database.BatchableContext BC, List<sObject> scope)
{
    //start method logic here
}
global void finish(Database.BatchableContext BC)
{
    //Batch Chaining Step Starts here
    AccountBatch accBatch = new AccountBatch ();
    Id batchProcessId = Database.executeBatch(accBatch);
    //finish method logic here
}
6. What interface will you use for batch apex?

It is Database.Batchable interface.

7. Why use Batch Apex in Salesforce instead of normal Apex?

There are various reasons why Batch Apex is better than normal Apex:

8. How many active batches (running parallel) can be allowed at a time?

Salesforce by default allows 5 active batches running at a time and other batches will be in queue for running.

9. Why use a Batch class as we already have data loader to process bulk data?

Agree with this point if and only if the data needs to be updated is static or predefined or which can be done through excel.

We will choose batch class if we have to perform some custom calculations at run time or if you want to run some complex logic which can’t be driven by excel sheets. In those cases, we have to go with batch classes.

Examples:

10. How many times will the execute method be executed to process 1234 records?

It depends on your batch size what you have configured at the time of calling the batch class from schedule class.

Execution method count = Total No Of Records / Batch Size (Any decimal ceil it to upper value)

If you haven’t set any batch size then – 1234/200 = 6.17 = 7 times execute method will be called.

11. What is the maximum size of a batch that we can set up?

2000

12. What is the minimum batch size we can set up?

1

13. What is the default size of batch if we haven’t configured at the time of execution?

200

14. What is Apex Flex Queue?

At a time Salesforce allows 5 batches to be running or to be in queued state. So, if you have consumed all these 5 limits and if the system has received one or more batch execution requests, all these waiting batches will be stored in this Apex Flex Queue.

15. What is the maximum number of batch classes allowed in Apex Flex Queue for execution?

100

16. Why call only from the finish method, why not from execute?

It is because the execute method gets invoked multiple times based on the volume of the records and batch size. So, if you’re calling it from the execute method then the chaining class will get called multiple times which is not a suggested way of doing it.

17. What is the difference between queryLocator object and Iterable used in batch apex?

With a QueryLocator object, 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.

18. What is the state of batch apex?

Batch Apex is typically stateless. Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and uses the default batch size is considered five transactions of 200 records each.

19. What is the use of Database.Stateful?

If you specify Database.Stateful in the class definition, you can maintain state across all transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Maintaining state is useful for counting or summarizing records as they’re processed.

20. When to use batch apex instead of Queueable Apex?

You should only use Batch Apex if you have more than one batch of records. If you don’t have enough records to run more than one batch, you should use Queueable Apex.

21. How to use HTTP Callouts in batch class?

To use HTTP Callouts in a batch class we need to use Database.AllowsCallouts in the interface.

22. If a batch is having 200 records and 1 record fails what will happen?

If any record fails and uses standard DML, all 200 records will fail, but the next batch will get executed.

23. Can we call the batch into another batch apex?

Yes, we can call from the finish method.

24. Can we call batch apex into another batch in execute method?

Only in the batch class finish method can we call another batch class. If you call another batch class from the batch class execute and start method, Salesforce will throw the below runtime error:

System.AsyncException: Database.executeBatch cannot be called from a batch start, batch execute, or future method.
25. Can we call the batch apex from triggers in salesforce?

Yes, it is possible. We can call a batch apex from a trigger but we should always keep in mind that we should not call batch apex from a trigger each time as this will exceed governor limits due to the constraint that we can only have 5 apex jobs queued or executing at a time.

26. How many times do start, execute, finish methods execute in batch apex?

Start method and finish method execute one time each. The execute method depends on requirements, based on the batch size and data retrieved in the Start method.

27. Can we call the future method in batch class?

No, we can’t call it directly from execute/start.

28. Can I call Queueable from a batch?

Yes, but you’re limited to just one System.enqueueJob call per execute in the Database.Batchable class. Salesforce has imposed this limitation to prevent explosive execution.

29. How to test batch apex?

Code is run between Test.startTest and Test.stopTest. Any asynchronous code included within Test.startTest and Test.stopTest is executed synchronously after Test.stopTest.

30. How many records can we insert while testing batch apex?

We have to make sure that the number of records inserted is less than or equal to the batch size of 200 because test methods can execute only one batch. We must also ensure that the Iterable returned by the start method matches the batch size.

31. What is apex Flex Queue?

The Apex Flex queue enables you to submit up to 100 batch jobs for execution. Any jobs that are submitted for execution are in holding status and are placed in the Apex Flex queue.

32. Can you change order of job in Apex Flex Queue?

Jobs are processed first-in first-out. You can look at the current queue order and shuffle the queue to move an important job to the front:

Boolean isSuccess = System.FlexQueue.moveBeforeJob(jobToMoveId, jobInQueueId);
33. Explain status of jobs in Apex Flex Queue?
34. Let’s say, I have 150 Batch jobs to execute, Will I be able to queue them in one go?

Once you run Database.executeBatch, jobs are placed in the Apex flex queue. Since the Flex queue has a maximum limit of 100 jobs, throwing a LimitException occurs if exceeded. Furthermore, concurrent active execution is limited to 5.

35. Can I Use FOR UPDATE in SOQL using Database.QueryLocator?

No, we can’t. It will throw an exception stating that “Locking is implied for each batch execution and therefore FOR UPDATE should not be specified”.

36. Can I query related records using Database.QueryLocator?

Yes, you can do subqueries for related records, but with a relationship subquery, batch job processing becomes slower. A better strategy is to perform the subquery separately from within the execute method.

36 (Alt). Can you write a batch class blueprint?
global class batchExample implements Database.Batchable<sObject> {
    global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {
        // collect batches of records
    }
    global void execute(Database.BatchableContext bc, List<sObject> records){
        // process each batch
    }
    global void finish(Database.BatchableContext bc){
        // post-processing
    }
}
37. Let’s say, we have run an apex batch to process 1000 records with batch size 200. An error occurs on the 395th record, what happens?

In batches, failures are scoped to the batch transaction. The first batch (records 1–200) succeeds and commits. If the second batch encounters an unhandled exception, that batch (records 201–400) rolls back.

38. How can you stop a Batch job?

The Database.executeBatch and System.scheduleBatch methods return an ID that can be used in the System.abortJob method.

39. Can we call future method in batch class?

Methods declared as future can’t be called directly from a Batch Apex execute/start method.

40. How to use Aggregate queries in Batch Apex?

Aggregate queries don’t work natively in Batch QueryLocators because they don’t support queryMore(), throwing errors. Use Iterables or standard SOQL loops instead.

41. What is the difference between database.batchable & database.batchablecontext bc?

Database.Batchable: An interface acting as a blueprint telling Salesforce your class is ready for batch processing.

Database.BatchableContext: A context variable storing runtime information about the batch job, like the job ID.

42. What if you change the name of Execute method to Execute1 in the batch class? Will it run?

It won't let you save the class as it violates the Database.Batchable interface contract.

43. Is there a way in which I can call a future method from a batch Job?

Calling a future method directly is not allowed in the Execute method, but web services or Queueable Apex can act as intermediaries.

44. What is batchable context? Why do we need it?

It stores runtime information such as the Job ID and gives context to the batch execution methods.

45. Can I write methods other than start, execute, finish?

Yes, you can write helper methods, but only start, execute, and finish are defined by the Database.Batchable interface.

46. Why is a batch class global?

Global makes a class usable by code outside of its defining namespace or managed package.

47. insert vs database.insert?

Standard DML (insert) rolls back or throws exceptions on bulk errors, whereas Database methods allow partial processing using allOrNone settings.

48. database.insert vs Stateful?

Database.insert handles DML behavior per transaction, while Database.Stateful maintains member variable states across distinct batch transactions.

49. Is finish asynchronous?

The finish method is synchronous; it runs immediately after the last execute transaction finishes without entering an execution queue.

50. What do we do to do callouts from batch?

1. Use Database.AllowsCallouts interface at the class level.
2. Perform callouts inside the execute method.

51. Can we do callouts from start method?

Callouts are not supported in the start method because it breaks query locator processing rules and hits governor limits.

52. Can we call queueable from batch?

Yes, queueables can be called from the finish method of a batch.

53. Can I call a batch from another batch?

Yes, you can chain them from the finish method.

54. Can we get records without querying a batch?

Yes, by using an Iterable implementation to pass pre-collected collections or objects.

55. How to run Future Methods?

Annotate a static void method with @future. Parameters must be primitive data types or collections of primitives.

56. What are Primitive Values and why pass them in future methods?

Primitives are immutable and simple, ensuring data integrity doesn't break between the time of method queueing and asynchronous execution.

57. How to call future methods?
ClassName.methodName();
58. Scenarios when we use future methods?

1. Background execution.
2. Mixed DML isolation (Setup and Non-setup objects).
3. Performing callouts from triggers.

59. What are Limitations of Future methods?

1. Cannot call another future method.
2. Only accepts primitive data types/collections.
3. Order of execution is not guaranteed.

60. Can you write the syntax of a future method?
global class FutureClass {
    @future
    public static void myFutureMethod() {
        // Perform operations
    }
}
61. What could be the workaround for sObject types in future methods?

Pass a collection of sObject IDs instead of the sObject instances, then query fresh records inside the future method.

62. How can I perform Callouts from Future methods?

Add the callout parameter to the annotation:

@future(callout=true)
public static void doCallouts(String name) {
    // Perform callout
}