How to limit trigger execution to avoid Too Many SOQL Queries: 101 errors?

How to limit trigger execution to avoid Too Many SOQL Queries: 101 errors?

On January 16, 2024, Posted by , In Salesforce, With Comments Off on How to limit trigger execution to avoid Too Many SOQL Queries: 101 errors?

How to limit trigger execution to avoid Too Many SOQL Queries: 101 errors?

Scenario:

Suppose you have a trigger on the Contact object that updates related Account records when certain fields on the Contact are modified. You want to ensure that the trigger only executes when necessary.

Original Trigger (Without Execution Limits):

In this original example, the trigger executes every time a Contact record is updated, regardless of whether the relevant fields have changed.

trigger ContactTrigger on Contact (before update) {
    for (Contact con : Trigger.new) {
        Account acc = [SELECT Id, CustomField__c FROM Account WHERE Id = :con.AccountId];
        acc.CustomField__c = 'Updated Value';
        update acc;
    }
}

Read more: Loops – Salesforce Apex

Optimized Trigger (With Execution Limits):

In the optimized trigger, execution is limited to only occur when specific fields on the Contact are modified, reducing unnecessary logic execution and SOQL queries.

trigger ContactTrigger on Contact (before update) {
    Set<Id> accountIdsToUpdate = new Set<Id>();
    for (Contact con : Trigger.new) {
        Contact oldCon = Trigger.oldMap.get(con.Id);
        // Check if specific fields have changed
        if (con.FirstName != oldCon.FirstName || con.LastName != oldCon.LastName) {
            accountIdsToUpdate.add(con.AccountId);
        }
    }

    // Only execute logic if there are accounts to update
    if (!accountIdsToUpdate.isEmpty()) {
        List<Account> accountsToUpdate = [SELECT Id, CustomField__c FROM Account WHERE Id IN :accountIdsToUpdate];
        for (Account acc : accountsToUpdate) {
            acc.CustomField__c = 'Updated Value';
        }
        update accountsToUpdate; // Perform a single DML operation
    }
}

Read more: Collections in Salesforce Apex

In this optimized code, the trigger first checks if the FirstName or LastName fields on the Contact have changed. If they have, the related Account is added to a set for updating. After collecting all affected Account IDs, a single SOQL query retrieves the relevant Account records, and a single DML operation updates them. This approach significantly reduces the number of SOQL queries and DML operations, helping to avoid the “Too Many SOQL Queries: 101” error.

Comments are closed.