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

  • Is that checkbox field also an opportunity field?
    – highfive
    Commented Jul 22, 2014 at 15:33

1 Answer 1


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) {
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).

  • 2
    Shouldn't you be referencing trigger.oldMap for old ? Commented Jul 22, 2014 at 15:38
  • 1
    I should have just edited....always forget I can do that, sorry Commented Jul 22, 2014 at 15:42
  • Hi guys, thanks so much for the help here. Using some kind of If Statement was my first thought, but then I figured I'd just be putting my SOQL statements in the loop of triggers so I decided against it. I hadn't considered using a set before and then updating after. This works great. Thanks again for the help, much appreciated.
    – Jay
    Commented Jul 22, 2014 at 15:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .