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
louisa barrett 7louisa barrett 7 

Query limits on triggers

Could someone offer me an explanation as to why this trigger from the APEX developer guide would exceed SOQL limits?

---------------------------------------------------
This is another example of a flawed programming pattern. It assumes that fewer than 100 records are pulled in during a trigger invocation. 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 completely understand why you shouldn't do this, but I don't understand how 20 records in the trigger would exceed 100 SELECT statements.

Could someone also confirm if the below is considered correct, my understanding would be this would only use 1 SELECT statement and the query would not be re-run over each iteration.

trigger oppTrigger on Opportunity (before delete) {
    for (Quote__c q : [SELECT opportunity__c FROM quote__c 
                       WHERE opportunity__c IN :Trigger.oldMap.keySet()]) {
        Trigger.oldMap.get(q.opportunity__c).addError('Cannot delete 
                                                       opportunity with a quote');
    }
}

Many thanks
 
Steven NsubugaSteven Nsubuga
The statement about 20 records is a mistake, especially when you consider that the previous statement mentioned 100 records. I believe the 20 is a typo, because triggers handle up to 200 records at a time.

The trigger you wrote is correct, the query will run once for all the records in the trigger.