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
ElectronElectron 

Trigger: Should put update inside loop or outside

Hi Everyone, when I faced the too many queries error, then I realize how important this article is 

http://wiki.developerforce.com/page/Apex_Code_Best_Practices

 

And I update all my code, use List for sObject, and put all queries out of loop. \

But it doesn't tell how to Where the update

 

Now I put update into the loop, because I have conditional statement.

 

Is there some method could check if List is changed or not? then update it? 

Best Answer chosen by Admin (Salesforce Developers) 
SurekaSureka

Hi,

 

Try the following logic:

 

trigger triggername on Account(after update)

{

List<Account> accs = new List<Account>();

for(Account a: trigger.new)

{

if(a.name == 'test')

{

Account a1 = a;

a1.newfield__c = 'test';

accs.add(a1);

}

}

 

update accs;

 

}

 

So if you have a criteria, put the logic inside and have the DLM statement outside the FOR Loop.

 

Thanks

All Answers

SurekaSureka

Hi,

 

Try the following logic:

 

trigger triggername on Account(after update)

{

List<Account> accs = new List<Account>();

for(Account a: trigger.new)

{

if(a.name == 'test')

{

Account a1 = a;

a1.newfield__c = 'test';

accs.add(a1);

}

}

 

update accs;

 

}

 

So if you have a criteria, put the logic inside and have the DLM statement outside the FOR Loop.

 

Thanks

This was selected as the best answer
vishal@forcevishal@force

Search for this statement on the link provided by you

 

//Now outside the FOR Loop, perform a single Update DML statement. 

update contactsToUpdate;

 

 

It is clearly given there.

 

And BTW, for a before insert/update trigger you don't need to specify an update statement. It happens on its own.

ElectronElectron

Thank you again, I didn't notice it. 

ElectronElectron

Thank you so much.

 

I also find if that a List could also be in the bracket, too.