How to use Batch Apex to avoid Too Many SOQL Queries: 101 errors?

How to use Batch Apex to avoid Too Many SOQL Queries: 101 errors?

On January 23, 2024, Posted by , In Salesforce, With Comments Off on How to use Batch Apex to avoid Too Many SOQL Queries: 101 errors?

How to use Batch Apex to avoid Too Many SOQL Queries: 101 errors?

Scenario:

Suppose you need to update all Contact records with a new field value based on related Opportunity data. Due to the large number of records, this operation is prone to hitting governor limits.

Batch Apex Class:

global class ContactOpportunityBatch implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext bc) {
        // Query all Contacts that need to be updated
        return Database.getQueryLocator([
            SELECT Id, AccountId, CustomField__c
            FROM Contact
            WHERE AccountId IN (SELECT AccountId FROM Opportunity WHERE StageName = 'Closed Won')
        ]);
    }
    //code is given below

        // Perform bulk update
        update contacts;
    }

    global void finish(Database.BatchableContext bc) {
        // Final processing (if needed)
    }
}

Read more: Collections in Salesforce Apex

Executing the Batch Apex Class:

You can execute the batch class from the Developer Console, an Apex trigger, or a scheduled job. Here’s an example of how to execute it from the Developer Console:

Database.executeBatch(new ContactOpportunityBatch(), 200); // Specify the batch size (optional)

In this Batch Apex class, the start method queries all Contact records that need to be updated. The execute method processes these records in batches, retrieving related Opportunity data and updating the Contact records as needed. By using Batch Apex, each batch of records is processed within its own set of governor limits, reducing the risk of hitting the “Too Many SOQL Queries: 101″ error.

Comments are closed.