0

I have come across the Salesforce documentation on Trigger and Bulk Request Best Practices.

Here is the link Trigger and Bulk Request Best Practices

They have explained that " If more than 20 records are pulled into this request, the trigger would exceed the SOQL query limit of 100 SELECT statements:"

trigger MileageTrigger on Mileage__c (before insert, before update) { for(mileage__c m : Trigger.new){ User c = [SELECT Id FROM user WHERE mileageid__c = m.Id]; } }

I could not understand what makes the trigger exceed SOQL query limit of 100 select statements if 20 records are pulled into this request. Could some one please clarify on this.

  • This is typo. It should be either 100 or 200 – Himanshu Nov 3 '17 at 7:13
  • Hi Himanshu Still I could not understand the meaning of it. – Prasanth Srinivasan Nov 3 '17 at 8:29
1

Trigger runs in 200 records batch. When you create any record using UI you can create only one record so your trigger will execute only once unless you have any workflow on your object (Read trigger lifecycle) but if you are inserting 400 records using data loader Salesforce executes trigger two times. i.e. two hundred records batch

so when you have code like this

trigger MileageTrigger on Mileage__c (before insert, before update) { 
   for(mileage__c m : Trigger.new){
     User c = [SELECT Id FROM user WHERE mileageid__c = m.Id]; 
   }
 }

It means that Saleforce will execute this mileage trigger only two times with 200 records batch. In this trigger you will notice that SOQL is inside for loop which will get executed 200 times and it exceed 100 soql limit.

We can optimize above code in following manner where we are executing soql only once.

trigger MileageTrigger on Mileage__c (before insert, before update) { 


Map<Id,User> mapUser = new Map<Id,User>([SELECT Id FROM user WHERE
mileageid__c = trigger.newmap.keyset()]); 

}
  • Thanks Himanshu. Now I understood, so during the first execution context a uncaught exception named Too Many SOQL queries will be thrown at 101 record right. – Prasanth Srinivasan Nov 3 '17 at 9:22
  • yes that is correct – Himanshu Nov 3 '17 at 9:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.