Sub topic 12
Writing triggers that handle up to 200 records per batch
This chapter assumes you know basic Apex syntax, collections (List, Set, Map), SOQL and DML, and the main governor limits. It shows how to write trigger logic that stays within those limits when many records arrive at once.
Why triggers receive batches
A trigger does not run once per record. Salesforce passes records to it in chunks of up to 200. A single insert of 500 Accounts runs the trigger three times, with 200, 200 and 100 records in Trigger.new. Data loads, API calls and list views that update many rows all behave this way.
The governor limits apply to the whole transaction, not to each chunk. The synchronous limits are 100 SOQL queries and 150 DML statements. A SOQL query or DML statement inside a loop spends that budget once per record, so it fails as soon as the batch is large enough.
The bulk-safe pattern
Follow four steps:
- Loop over
Trigger.newand collect the Ids you need into a Set. - Run one SOQL query outside the loop.
- Put the results in a Map for fast lookup.
- Loop again, read from the Map, and collect any records to write into a List. Run one DML statement after the loop.
Example: tasks for open opportunities
This trigger creates a follow-up Task for each Account that has open Opportunities. The unsafe version queries inside the loop. The version below queries once.
trigger AccountOpenOppTask on Account (after update) {
// Step 1: collect Ids
Set<Id> accountIds = new Set<Id>();
for (Account a : Trigger.new) {
accountIds.add(a.Id);
}
// Step 2 and 3: one query, grouped into a Map
Map<Id, Integer> openCounts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acc, COUNT(Id) cnt
FROM Opportunity
WHERE AccountId IN :accountIds AND IsClosed = false
GROUP BY AccountId
]) {
openCounts.put((Id) ar.get('acc'), (Integer) ar.get('cnt'));
}
// Step 4: loop, then a single DML
List<Task> tasks = new List<Task>();
for (Account a : Trigger.new) {
if (openCounts.containsKey(a.Id)) {
tasks.add(new Task(
Subject = 'Review ' + openCounts.get(a.Id) + ' open opportunities',
WhatId = a.Id
));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}With 200 Accounts, this uses one SOQL query and one DML statement. The unsafe version would use 200 queries and fail on the 101st.
Common mistakes
- Assuming one record. Code such as
Trigger.new[0]ignores the other 199 records. Always loop. - SOQL or DML in a loop. This includes calls to a helper method from inside a loop, because the helper's queries still count.
- Querying without a filter set. Use
WHERE Id IN :idswith a Set, not a query that returns everything. - DML on an empty list. It does not fail, but it still counts as a DML statement, so guard it with
isEmpty(). - Forgetting that other code shares the limits. Flows, other triggers and the calling code run in the same transaction. Stay well under the limits.
Check your understanding
Exercise
A trigger on Contact runs [SELECT Name FROM Account WHERE Id = :c.AccountId] inside for (Contact c : Trigger.new). A user imports 150 Contacts. What happens, and how do you fix it?
Show answer
The loop runs one query per Contact, so the 101st query throws a "Too many SOQL queries: 101" exception and the whole transaction rolls back. To fix it, collect the AccountId values into a Set in a first loop, run one query with WHERE Id IN :accountIds, store the results in a Map<Id, Account>, and read from the Map in a second loop.