System.Exception: Too many SOQL queries: 101 [duplicate]

I am getting a Too many SOQL queries: 101 error on a trigger when I am trying to deploy another trigger.

I am posting the trigger which is causing the error.

trigger rollupAccountShowings on Account (before insert, before update) {
   if (trigger.isinsert) {
      for (Account a:Trigger.new){
          a.No_of_Viewings__c = 0;
       }
   } else {
     for (account a : [select 
                 id,
                 (select id from pb__Showings__r)
                 from account 
                 where id in:trigger.new LIMIT 1]) {

         trigger.newMap.get(a.id).No_of_Viewings__c = a.pb__Showings__r.size();
     }
}

Can anyone correct me where I have gone wrong and suggest me the changes.

Thanks

Answer

The code in your trigger is fine.

The trigger or class that the Too many SOQL queries: 101 error is thrown on may or may not be the cause of the problem. It just means that the code in question made the 101st SOQL call, which hit the SOQL limit.

As the comments on your question state, the most common cause of the 101 error is that you have a SOQL query in a FOR LOOP. If you can’t find the loop thats causing the problem then one way to debug this issue is to turn on debug logging and then reproduce the problem. If you search the debug logs for SOQL_EXECUTE_BEGIN you should find 101 references (once you haven’t hit the max log size).

The SOQL queries will be displayed something like what is shown below.

03:57:09.030 (30409851)|SOQL_EXECUTE_BEGIN|[70]|Aggregations:0|select Id, Email from User where Id = :tmpVar1

03:57:09.033 (33956239)|SOQL_EXECUTE_END|[70]|Rows:1

You should find that the vast majority of your SOQL statements are caused by the same query. Once you know which query it is you can find it in your code and then remove it from the loop it is in.

Attribution
Source : Link , Question Author : user4675 , Answer Author : Community

Leave a Comment