Salesforce: System.LimitException: Too many SOQL queries: 101

This is a common error for those who write trigger. This is caused by Salesforce Execution Governors and Limits.

Bad example:

 

for(Account acc : Trigger.new) {
   List<Contact> conList = [SELECT id FROM Contact WHERE AccountId =: acc.Id] ;
}

 

If there are more than 100 accounts created/updated at the same time using data loader or similar mechanism, the trigger will execute the query more than 100 times.

 

 

Recommend approach:

 

Map<Id, List<Contact>> conMap = new Map<Id, List<Contact>>();

//We will query the related contacts from Salesforce and load them into a Map
for(Contact con : [SELECT id FROM Contact WHERE AccountId IN: Trigger.new]) {
    // Check if entry exists in Map
    if(conMap.containsKey(con.AccountId))
        conMap.get(con.AccountId).put(con.AccountId, con);
    else {
        List<Contact> newConList = new List<Contact>();
        newConList.add(con);
        conMap.put(con.AccountId, con)
    }

//Here, we loop through the account from the Trigger.new and get the related contacts out from the Map that we have prepared above

for(Account acc : Trigger.new) {
     List<Contact> conList = conMap.get(acc.Id);
}