Bulk Apex Triggers #inSalesforce

Bulk Apex Triggers


The Difference:

//MyTriggerNotBulk 
trigger MyTriggerNotBulk on Account(before insert) {
    Account a = Trigger.new[0];
    a.Description = 'New description';
}

//MyTriggerBulk 
all records covered
trigger MyTriggerBulk on Account(before insert) {
    for(Account a : Trigger.new) {
        a.Description = 'New description';
    }
}


Example:

//SoqlTriggerNotBulk 
trigger SoqlTriggerNotBulk on Account(after update) {   
    for(Account a : Trigger.new) {
        //Get child records for each Account. Runs once for each account
        Opportunity[] opps = [SELECT Id,Name,CloseDate FROM Opportunity WHERE AccountId=:a.Id];
        //some operation...
    }
}

//SoqlTriggerBulk 

trigger SoqlTriggerBulk on Account(after update) {  
    // Perform SOQL query once. Get the related opportunities for the accounts and iterate over records.
    for(Opportunity opp : [SELECT Id,Name,CloseDate FROM Opportunity WHERE AccountId IN :Trigger.new]) {
        // some operation...
    }
}



For details check Reference.


Reference: https://trailhead.salesforce.com/content/learn/modules/apex_triggers/apex_triggers_bulk#:~:text=Bulk%20Trigger%20Design%20Patterns,-Apex%20triggers%20are&text=The%20benefit%20of%20bulkifying%20your,resources%20on%20the%20multitenant%20platform.

Comments