[SalesForce] Only execute Before Update trigger if conditions are met

I have a trigger on the opportunity object with the below format:

Before Update on Opportunity

  • Create List of ID's
  • Create Set Using SOQL Query
  • Create Map Using SOQL Query

Iterate over Opportunities in Trigger
If conditions are met – do something
If some other conditions are met – do something else

  • Update List

This works fine, however every time a user edits an opportunity, 2 SOQL queries are going to be run. Is there a way to only execute the trigger if a condition is met (in this case, a checkbox on the opp == true)?

Many thanks in advance

Best Answer

You can add this sort of guard in your trigger:

Set<Id> ids = new Set<Id>();
for (Opportunity opp : Trigger.new) {
    if (opp.Checkbox__c) {
        Opportunity old = Trigger.oldMap.get(opp.Id);
        if (opp.Checkbox__c != old.Checkbox__c) {
            ids.add(opp.Id);
        }
    }
}
if (ids.size() > 0) {
    // Query
}

so that the queries are only done if the checkbox is checked and when the checkbox value has changed (if that is appropriate too).