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
Lukesh KarmoreLukesh Karmore 

Apex trigger to update account rating when the opportunity stage equals closed won

my code is -
trigger UpdateAccRatingToHot_WhenOppStageIsClosedWon on  Opportunity ( before insert) {
    list<account> accounts =  new list<account>();
    for(account acc : [select name, rating from account]){
    for(opportunity opp : trigger.new){
        if(opp.stagename == 'closed won'){
            acc.Rating = 'Hot';
            accounts.add(acc);
        }
    }
  }update accounts;
}

It gives me error of too many SOQL queries Why??
ShirishaShirisha (Salesforce Developers) 
Hi Lukesh,

Greetings!

You are getting this error because you are trying to query the records inside the loop and the query is running more than 100 times.

Reference:https://help.salesforce.com/articleView?id=000331875&type=1&mode=1

I don't think you need to query the records here.You can simply use the list to update the rating field.

Please mark it as best answer if it helps you to fix the issue.

Thank you!

Regards,
Shirisha Pathuri
Malika Pathak 9Malika Pathak 9
Hi Lukesh Please try this 

trigger UpdateAccRatingToHot_WhenOppStageIsClosedWon on  Opportunity ( before insert) {
set<id> AccountIdset = new set<id>();
for(opportunity opp : trigger.new){
AccountIdset.add(opp.AccountId);
}
    list<account> accountList =  new list<account>([select name, rating from account where id in: AccountIdset ] );
  for(account acc : accountList){
    for(opportunity opp : trigger.new){
        if(opp.stagename == 'closed won' && acc.id == opp.AccountId){
            acc.Rating = 'Hot';
            accounts.add(acc);
        }
    }
  }update accounts;
}

Please mark your best Answer