function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Zach CarterZach Carter 

Filter by DB call or conditional checks?

Hello,

 

Let's say I have a bulk trigger andI only want to perform the business logic of the trigger when an sobject in the collection the trigger is operating on, has  a certain field filled out (not null).

 

Is the cheapest way to do this to iterate over the conents of the trigger until I find a sobject with a not null value in this field? Something like - 

 

for(Account a : Trigger.new) {
    if(a.customField != null) {

      // add object to collection

      ...

   }
}

 

This is O(N) and while I don't expect bulk creation of account objects to occur I suppose it is always possible.

 

I chose this option instead - 

 

Account[] changedAccounts = [SELECT Id, customField FROM Account WHERE Id IN :Trigger.new AND customField != null];

 

Then I iterate over this collection, however I have the EXACT collection I want.

 

I wish there were more fine grained control over when a trigger fires in Apex, but then again there are a lot of other more important features the language lacks so I suppose as long as I find the most efficient way to filter my result set I'll be happy for now.

 

Thanks,

 

-Zach

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

Iterate over the trigger members whenever possible. You have far more "script statements" (200,000) compared to database calls (100).

All Answers

sfdcfoxsfdcfox

Iterate over the trigger members whenever possible. You have far more "script statements" (200,000) compared to database calls (100).

This was selected as the best answer
Zach CarterZach Carter

Alright but it still seems very inefficient. Isn't there a way to fire off the trigger conditionally, like only when a certain field is populated?

 

Some things about SFDC don't make a lot of sense to me... this is one of them. Seems like an extremely inefficient way to narrow a result set.

 

 

 

 

sfdcfoxsfdcfox

No, but if you think about it, a conditional check at the system level is no more efficient than at the apex code level; all you'd be doing is shifting responsibility from one layer of software to another. Your version would have one benefit though: you could alter the parameters without coding, like how workflow rules work.