function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nitin sharma 425Nitin sharma 425 

Governor limit for simple query in a regular class versus Batch class

Hi All,

Firstly,Governor limits for a single query such as [Select id,name from Account] wiill fetch 50,000 thousand records as per salesforce Governor limits.
and now same Query in the Start() method of the batch class can fetch 50 million account records,Is that correct?.please correct me if I am wrong.

Thirdly,am not sure how these 50 millions records are processed.
My guess is salesforce will keep on passing 50 million records in chunks of 200 each to the Execute() which will process those records and then next set of 200 records will be passed to the execute methis.Will keep doing it unless all 50 million records are processed.

Am I thinking right?...Though I am going through the documentation,.However would like to hear from people out there in the community.
Thanks


 
Suraj Tripathi 47Suraj Tripathi 47

Hi Nitin,

Yes, You are right.

Just read my post and it will clear your all doubt.

Advantages of Batch Apex in Salesforce

1. Whenever a transaction is executed, Batch Apex ensures that the code stays within the governor limit.
2. Until a batch is not successfully executed, Batch Apex won’t execute the following batches.
3.A large set of records can be processed together on a regular basis using Batch Apex classes.
4.The interface can be scheduled to run batches at different time periods.
5.Asynchronous operations can be implemented by Batch Apex classes.
6.Batch jobs are invoked programmatically during the runtime and can be operated on any size of records, with a maximum of 200 records per batch. You can break down a larger record data into 200 records per batch to execute it better.

Why use Batch Apex in Salesforce instead of the normal Apex?

There are various reasons why Batch Apex is better than normal Apex.
1. SOQL queries: Normal Apex uses 100 records per cycle to execute SOQL queries. Whereas, Batch Apex does the same in 200 records per cycle.
2. Retrieval of SOQL queries: Normal Apex can retrieve 50,000 SOQL queries but, in Batch Apex, 50,000,000 SOQL queries can be retrieved.
3. Heap size: Normal Apex has a heap size of 6 MB; whereas, Batch Apex has a heap size of 12 MB.
4. Errors: When executing bulk records, Normal Apex classes are more vulnerable to encountering errors as compared to Batch Apex.

 

Salesforce Batch Apex Job With Examples
Salesforce has governor limits which restrict us from processing huge amount of data. Some of the governor limits that puts restriction on the amount of data that we can process are listed below:
1. Maximum number of SOQL queries within a transaction: 100
2. Maximum number of DML statements within a transaction: 150
3. Maximum number of rows within a DML statement: 10000
4.Number of future methods within a transaction: 50
5.To overcome these governor limits, we can write a batch apex and process the data in chunks. To write a batch apex, we have to implement the Database.Batchable interface. This interface contains three methods.

Start Method: The signature of this method is

global (Database.QueryLocator | Iterable<sobject>) start(Database.BatchableContext bc) {}

This method is used to collect the records that we want to process. This method can return either Database.QueryLocator or an Iterable. The Database.QueryLocator return type is used when we want to run a simple select statement. With this return type, the select statement can return up to 50Million records. When we want to write a custom logic (like aggregations), then we have to use the Iterable return type. With this return type, the batch can only process a maximum of 50K records.

 

Execute Method: The signature of this method is

global void execute(Database.BatchableContext BC, List<sobject> scope){}
This method runs for each chunk of data and is used for processing the data. This method is executed for each batch of records.

Finish Method:  The signature of this method is

global void finish(Database.BatchableContext BC){}

This method is called after all the batches are completed and used for any clean up activities, checking job status and sending emails.

How to Execute the Batch Apex
The Database.Execute Method is used for running a batch apex. The signature of this method is

public static ID executeBatch(Object batchClassObject) // 200 records in each chunk
public static ID executeBatch(Object batchClassObject, Integer scope)


This method takes two parameters. The first parameter is the instance of the class that implements the Database.Batchable interface. The second parameter is an optional one for specifying the number of records to pass to the execute method. If the start method returns Database.QueryLocator, then the maximum number of records that can be processed in each batch is 2000. There is no upper limit for the Iterable return type.

Each batch of records is treated as an independent transaction. All the governor limits that apply for a single transaction are as well applicable for each chunk/scope of records. So we have to choose the chunk/scope size carefully so that it doesn't hit the salesforce governor limits.

The Database.Execute method returns the Id of the Batch Job which can be used to get the status of the by querying the AsyncApexJob object.

You can also take reference from this link.

 https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm

https://intellipaat.com/blog/tutorial/salesforce-tutorial/salesforce-batch-apex/

https://www.folkstalk.com/2020/03/salesforce-batch-apex-job-with-examples.html

If it will help you please mark it as Best Answer So that other people would take reference from it.

Thanks

Nitin sharma 425Nitin sharma 425

Thanks for your reply...On the basis of the explnation that you have given above.In one batch 200 Records are passed to the Execute method..After one Batch of records are processed then another batch of 200 records is passed to the Execute and so on unless all batches are fully processed.

My question:-

global class AccountBatchApex implements Database.Batchable<sObject>{
     
    global integer numberofDirectCustomers = 0;
    
     
    global Database.QueryLocator start(Database.BatchableContext bc){
        String soqlQuery = 'SELECT Name, AccountNumber, Type From Account';
        return Database.getQueryLocator(soqlQuery);
    }
     
    global void execute(Database.BatchableContext bc, List<Account> scope){
         counter=counter+1;
        system.debug('The counter is'+counter);
        for (Account acc : scope){
            if(acc.Type.equals('Customer - Direct'))
            {
                numberofDirectCustomers++;
                System.debug('The number of new cutomer are as follows'+numberofDirectCustomers);
                
            }
        }
    }
     
    global void finish(Database.BatchableContext bc){
         
    }
}


In the above code there is an Integer variable which has been set to zero.

global integer numberofDirectCustomers = 0;


within the for loop I am incrementing the varible and there are 400 records which are fullfilling the criteria in the for loop

So I was hoping that once 200 records are processed by the execute method then the integer variable will be reset to Zero and Processing of another set of 200 records will begin and integer variable will be reset to zero and keeping incrementing till all 200 records are proceessed.

However,the variable starts increamenting and keep incrementing till the time 400 records are not processed.There is no Database.stateful to maintain the state then how come variable it not reset to zero.

I guess I am missing something?

Thanks,
Nitin