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
Akshay MenseAkshay Mense 

Avoid Soql in for loop query with below example

Hello, I want to remove SOQL from for loop below is trigger. how to do it? 

trigger UpdateOwner on Suggestion__c (before insert) {
 
    for (Suggestion__c sugg : Trigger.new)
    {
        if (sugg.Rep_Email__c != null )
        {
            User usrLst = [SELECT Id, Name, Email FROM User WHERE Email =: sugg.Rep_Email__c];
            if(usrLst != null){
                sugg.OwnerId = usrLst.Id;
            }  
        }
    }
    

}
ANUTEJANUTEJ (Salesforce Developers) 
Hi Akshay,

You can try the below snippet and modify it accordingly.
 
trigger UpdateOwner on Suggestion__c (before insert) {
 if(trigger.isbefore && trigger.isinsert)
 {
 set<string> emailset = new set<string>();
 map<String,id> memail= new<String,id>();
 for(Suggestion__c sug: trigger.new)
 {
 if(sug.Rep_Email__c != null)
	{
	emailset.add(sug.Rep_Email__c);
	}
 }

 list<User> usrLst = [SELECT Id, Email FROM User WHERE Email in :emailset];

for(User u: usrLst)
{
	  memail.put(u.email, u.id);
}

for(Suggestion__c sug: trigger.new)
 {
 sugg.OwnerId = memail.get(sug.Rep_Email__c);
}
}

Please do note that this is a sample snippet and you need to modify it as needed.

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.