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
sibil joesibil joe 

how to avoid query inside a loop in trigger?

public static void setAccount(List<Account> newList){
    List<Account> pirList = new List<Account>();    
    List<Account> p1 = new List<Account>();
    for(Account newAcc: newList){
            
            if(newAcc.RecordTypeId == pirRecId){
                p1.add(newAcc);
                
                p1 = [SELECT id,FirstName,LastName,MiddleName 
                                FROM Account 
                                WHERE
                                FirstName =: newAcc.FirstName AND
                                LastName =: newAcc.LastName AND
                                MiddleName =: newAcc.MiddleName ];

                for(Account patient:p1){
                    patient.lookup = newAcc.Id;
                }
                update p1;
            }
        }    
   }
This function is called from a trigger in after insert
AnkaiahAnkaiah (Salesforce Developers) 
Hi sibil,

Please try with below code.
public static void setAccount(List<Account> newList){
    List<Account> pirList = new List<Account>();    
    List<Account> p1 = new List<Account>();
    for(Account newAcc: newList){
            
            if(newAcc.RecordTypeId == pirRecId){
                p1.add(newAcc);

                }
            }
			
			                
              List<Account>  acclist = [SELECT id,FirstName,LastName,MiddleName 
                                FROM Account 
                                WHERE
                                FirstName =: p1.FirstName AND
                                LastName =: p1.LastName AND
                                MiddleName =: p1.MiddleName ];
								
								
                for(Account newAcc: newList)
                  for(Account patient:acclist){
                    patient.lookup = newAcc.Id;
pirList.add(patient.lookup);
        }
If(pirList.size()>0){
		update acclist;
   		}
   }

If this helps, plese mark it as best answer.

Regards,
Ankaiah Bandi
sibil joesibil joe
Hi Ankaiah,

Thank you for your response!
However, given that p1 is a list, how is it possible to use p1.FirstName?

Thank you,
Sibil