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
RAMACHANDRA REDDY DONDETIRAMACHANDRA REDDY DONDETI 

Apex trigger contactaccountrelation caused an unexpected exception, contact your administrator: contactaccountrelation: System.LimitException: Too many SOQL queries: 101

AbhinavAbhinav (Salesforce Developers) 
Please share the code snippet as well.
RAMACHANDRA REDDY DONDETIRAMACHANDRA REDDY DONDETI
trigger contactaccountrelation on Contact (before insert) { 
list acc = [select id, name from account]; for(account a : acc){
 for(contact con : [select lastname, accountid, other phone from contact where accountid =: a.id])
{ con.OtherPhone = a.Phone; } } }

 
AbhinavAbhinav (Salesforce Developers) 
Your this
[select lastname, accountid, other phone from contact where accountid =: a.id] query inside the loop which is causing the isuue System.LimitException: Too many SOQL queries: 101. Its never a best practice to have query inside the loop.

Second issue with your code is:

you are pulling every account in this query select id, name from account which can give issue when is there is more record try to use filter in query as per you requirement.

If it helps please mark it as best answer.

Thanks!
Maharajan CMaharajan C
Hi Ram,

Please use the below trigger:

Don't use the SOQL Query inside for loop... Write the trigger in bulkified manner to avoid these kind of exceptions...
 
trigger contactaccountrelation on Contact (before insert) { 
    Set<Id> stAccId = new Set<Id>();
    for(Contact con : Trigger.New){
        if(con.AccountId != null)
            stAccId.add(con.AccountId);
    }
    
    if(!stAccId.IsEmpty()){
        map<Id,Account>  mapOfAcc = new map<Id,Account>([SELECT Id,Name,Phone FROM Account Where Id IN:stAccId]);
        for(Contact objCon : Trigger.New){
            if(objCon.AccountId != null && mapOfAcc.containsKey(objCon.AccountId))
                objCon.OtherPhone = mapOfAcc.get(objCon.AccountId).Phone;
        }
    }	
}

Thanks,
Maharajan.C