[SalesForce] How many times trigger will be invoked if I want to process 30K records

As per trailhead module :

Bulk Apex Triggers

trigger SoqlTriggerBulk on Account(after update) {  
    // Perform SOQL query once.    
    // Get the related opportunities for the accounts in this trigger,
    // and iterate over those records.
    for(Opportunity opp : [SELECT Id,Name,CloseDate FROM Opportunity
        WHERE AccountId IN :Trigger.New]) {

        // Do some other processing

Triggers execute on batches of 200 records at a time. So if 400
records cause a trigger to fire, the trigger fires twice, once for
each 200 records. For this reason, you don’t get the benefit of SOQL
for loop record batching in triggers, because triggers batch up
records as well. The SOQL for loop is called twice in this example,
but a standalone SOQL query would also be called twice. However, the
SOQL for loop still looks more elegant than iterating over a
collection variable!

I am processing 30K records and my trigger will be invoked 150 times.

Will I get SOQL 101 queries error if my trigger is invoked 1000 times?

Best Answer

Yes, you will get the 101 query exception1.

The reason is that all of the trigger "chunks" (I prefer using "chunk" over "batch", because "batch" in Salesforce is a separate thing) are part of the same transaction, and governor limits are enforced per-transaction.

If you use one query in your trigger, then your trigger can handle (at most) 20,000 records.

The number of records that you can handle decreases as your trigger becomes more complex (more queries and interactions with other triggers, workflow rules, or process builder).

Of course, the other limit that you need to worry about is the DML rows limit, which is a hard cap of 10,000 records per transaction.

1: Well, you would if Salesforce didn't restrict the number of DML rows. If you try to dml 30K records, I'd expect you to receive a DmlException for the number of DML rows before you'd get a QueryExceptionfor the number of queries

Related Topic