Batch apex is a critical topic in Salesforce interviews, as it pertains to handling large volumes of data efficiently. The performance of batch apex is essential to optimize bulk data processing. Here are some questions to help you clear your salesforce interviews.
Q.1 : What is Batch Apex and Why it is used?
Ans : Batch Apex is a powerful tool in Salesforce that enables the processing of large amounts of data in smaller, manageable chunks. As an asynchronous apex solution, Batch Apex provides a fresh set of governor limits for each transaction, ensuring that your code stays within the execution limits. This makes it ideal for data cleaning and archiving, making your data management more efficient and effective. With its ability to handle large volumes of data, Batch Apex is an essential component for any organization looking to optimize their Salesforce performance.
**Each batch is a transaction. The Apex governor limits are reset for each transaction.
Q.2 : What are the three methods in Batch apex?
Ans : The Start method is called only once at the beginning of the apex job and is used to collect all the records that need to be processed.
The Execute method is called multiple times, based on the number of records and the batch size. It is used to perform operations on the records fetched from the Start method.
Lastly, the Finish method is executed after all batches have been processed. It is commonly used for post-job tasks such as sending emails or performing any necessary clean-up actions.
Q.3 :What are the default and maximum batch sizes in Batch Apex?
Ans: The default batch size for batch processing is 200 and maximum is 2000 records.
Q.4: If an error occurs while processing the 200th record during a batch class execution, where the batch size is 200 and the total number of records being processed is 1000, what will be the outcome of the batch job?
Ans : In Batch Apex, if the first transaction succeeds but the second transaction fails, the updates made in the first transaction will not be rolled back. When the batch size is 200, the first batch is processed entirely and all the data is committed to the database. However, if we use normal DML statements like insert or update in the second batch, the entire batch will be rolled back, and records 201 to 400 will not be processed.
On the other hand, if we use Database DML operations such as Database.insert with AllOrNone as false, partial commit can occur. In this scenario, only the 400th record will not be processed in that batch, and a total of 199 records will be processed. This will not hamper the execution of the other batch.
Q.5: Is it possible to invoke a future method from a batch class in Salesforce?
Ans : No
Q.6: What is Database.Stateful?
Ans : When we process data in batches in Salesforce, we may need to keep track of how many records were processed successfully and how many had errors. To achieve this, we can use an Interface called Database.Stateful. It helps to retain the values of instance variables between transactions in batch apex. However, it’s worth noting that static variables don’t retain their values between transactions.
Q.7: What is the difference between Database.QueryLocator and Iterable<sObject>?
Ans: In Database.QueryLocator, we can use simple Select query to fetch the records from salesforce objects.It can return upto 50 million records.The start method in a batch class can return an iterator, which is useful for processing a large amount of data that cannot be queried directly from Salesforce or data obtained from two unrelated objects. These iterators can be classes that implement the Iterable interface or standard Apex data structures like a list.It can return upto 50k records.
Q.8: Can we use batch apex to call an external web service?
Ans: Yes by implementing Database.AllowsCallouts interface.
Q.9: Is it possible to use FOR UPDATE in a SOQL query when using Database.QueryLocator in Salesforce?
Ans : Using the “FOR UPDATE” clause in a SOQL query with Database.QueryLocator is not allowed in Salesforce. If attempted, an exception will be thrown with the message, “Locking is implied for each batch execution and therefore FOR UPDATE should not be specified.”
The reason behind this restriction is that including “FOR UPDATE” in a query for an entire database would cause the entire database to be locked as long as the batch is running.
Q.10: How to write test class for Batch Apex?
Ans : To test a Batch Class we need to call the batch job within Test.startTest and Test.stopTest as it gives new set of governor limits .Additionally, any asynchronous calls made after the startTest() method are collected by the system. When the stopTest() method is executed, all asynchronous processes are run synchronously. It is important to note that only one execution of the execute method can be tested, so it is necessary to set the batch scope according to the governor limits.
————————————– Batch Apex Example ——————————————–global class MyBatchClass 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> accounts){
for(Account acc : accounts){ acc.Name = acc.Name + ‘updated’;
}
try{
update accounts;
}catch(Exception e){
System.debug(‘Exception in account insert’,+ e);
}
} global void finish(Database.BatchableContext BC){
// execute any post-processing operation like sending email
}
}
———————————– Invoking a batch class —————————————-MyBatchClass myBatchObj = new MyBatchClass(); String batchId = Database.executeBatch(myBatchObj,100); AsyncApexJob job = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob WHERE ID = :batchId ];
———————————-Scheduling Batch Apex ———————————————global class scheduledBatchable implements Schedulable{
global void execute(SchedulableContext SC){
MyBatchClass myBatchObj = new MyBatchClass();
String batchId = Database.executeBatch(myBatchObj);
}
}