Sub topic 3
Triggers Handle Up to 200 Records at a Time
This chapter assumes you know basic Apex syntax, the List, Set and Map collections, basic SOQL and DML, and what the before and after trigger events are. It explains how a trigger receives records in batches. This is the fact that makes bulkification necessary.
A trigger runs once per batch, not once per record
Many developers picture a trigger as code that runs once for each record. It does not. Apex runs a trigger once for each chunk of records in a DML operation. The platform hands the trigger a collection, and your code must handle every record in it.
When a DML statement or API call changes many records, the platform splits them into chunks of up to 200. Each chunk causes one trigger invocation. Insert 450 Contacts with one insert statement and the trigger runs three times in the same transaction, with 200, 200 and 50 records.
Because all the chunks belong to one transaction, they share one set of governor limits. A query that runs once per record therefore counts against the same 100 synchronous SOQL query limit across all chunks.
The 200-record chunk size applies to DML from Apex, the SOAP API, Data Loader with its default settings, and most other sources. Some sources send smaller batches. A user who saves one record in the UI produces a batch of one. A trigger that works for a batch of one and fails for a batch of 200 is a typical bulkification bug, and it often goes unnoticed until a data load or integration reaches production.
The context variables that carry the batch
Inside a trigger, the platform exposes the records through context variables on the Trigger class. Each of the collection variables holds the whole batch.
| Variable | Type | Available in | Contents |
|---|---|---|---|
| `Trigger.new` | `List<SObject>` | insert, update, undelete | The new versions of the records |
| `Trigger.old` | `List<SObject>` | update, delete | The old versions of the records |
| `Trigger.newMap` | `Map<Id, SObject>` | before update, after insert, after update, after undelete | New versions keyed by Id |
| `Trigger.oldMap` | `Map<Id, SObject>` | update, delete | Old versions keyed by Id |
| `Trigger.size` | `Integer` | all events | Total number of records in the invocation |
Some details matter in practice:
Trigger.newis not available in delete triggers, andTrigger.oldis not available in insert triggers.- In a before insert trigger, records have no Id yet, so
Trigger.newMapdoes not exist there. ReadingTrigger.newMapin that event gives younull. Trigger.newis read-only in after triggers. You can change field values on records inTrigger.newonly in before triggers, and those changes are saved without a DML statement.Trigger.newandTrigger.oldare in matching order for update triggers, but relying on index position is fragile. UseTrigger.oldMap.get(record.Id)to find the old version of a record.
Boolean context variables
The platform also tells the trigger which event fired it. A trigger declared for several events can branch on these variables.
trigger ContactAll on Contact (before insert, before update, after insert) {
if (Trigger.isBefore && Trigger.isInsert) {
System.debug('Before insert with ' + Trigger.size + ' records');
} else if (Trigger.isBefore && Trigger.isUpdate) {
System.debug('Before update with ' + Trigger.size + ' records');
} else if (Trigger.isAfter && Trigger.isInsert) {
System.debug('After insert with ' + Trigger.size + ' records');
}
}The variables include Trigger.isBefore, Trigger.isAfter, Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete and Trigger.isUndelete. Each one is true or false for the current invocation. Note that Trigger.isExecuting is true whenever the code is running inside a trigger context.
Writing the loop that handles the batch
The basic shape of a bulk-safe trigger is a loop over Trigger.new. The loop itself is fine. The risk is what you put inside it.
trigger ContactBefore on Contact (before insert) {
for (Contact c : Trigger.new) {
if (String.isBlank(c.Description)) {
c.Description = 'Created through trigger';
}
}
}This trigger uses only field reads and writes inside the loop. These operations consume CPU time but no SOQL queries or DML statements, so they are safe for any batch size.
The version below shows the opposite. It looks reasonable for one record, but it queries inside the loop.
trigger ContactBefore on Contact (before insert) {
for (Contact c : Trigger.new) {
// Anti-pattern: one query per record
Account a = [SELECT Id, Industry FROM Account WHERE Id = :c.AccountId];
c.Description = 'Industry: ' + a.Industry;
}
}With a batch of one, this trigger uses one query. With a batch of 200, it uses 200 queries, which is over the limit of 100 for synchronous Apex. The transaction fails with a System.LimitException: Too many SOQL queries: 101. The same code also has a second flaw. If c.AccountId is null, the query returns no rows and assigning to a single Account variable throws a QueryException.
Chapter notes on the fix come later in this tutorial. For now, the key idea is the shape of the correct solution: collect what you need from the whole batch in one loop, query once, then use the results in a second loop.
The three-pass pattern
Most bulk-safe triggers follow the same three steps.
- Loop over
Trigger.newand collect keys, such as parent Ids, into aSet. - Run one query that uses the Set in an
INclause, and store the results in aMap. - Loop over
Trigger.newagain and read from the Map to do the per-record work.
trigger ContactBefore on Contact (before insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account a = accounts.get(c.AccountId);
if (a != null) {
c.Description = 'Industry: ' + a.Industry;
}
}
}The trigger now runs one query whether the batch holds 1 record or 200. The null check on AccountId avoids putting null into the Set, and the null check on the lookup result handles Contacts whose Account was not found. Calling accounts.get(null) is safe and returns null, but the explicit checks make the intent clear.
Triggers fire in a chain, and each link gets its own batch
A single user action can start a chain of trigger invocations. A trigger on Account that inserts Tasks starts the Task triggers. A workflow field update, a flow, or a process can cause an update that fires the same object's triggers again. Each of these invocations receives its own batch, but they all run in the same transaction and share its limits.
This has two consequences:
- A trigger that is bulk-safe on its own can still fail when another automation in the chain has already used most of the queries or DML statements.
- A trigger can be invoked more than once in a transaction for the same records, for example after a field update. Do not assume it runs once per save.
The chapter on recursion control later in this tutorial covers how to stop repeated invocations. The chapter on the Limits class shows how to see how much of the shared budget is left.
Mixed batches in update triggers
An update trigger often receives records that changed in different ways. Some records in the batch may have the field you care about changed, and others may not. A bulk-safe trigger filters the batch first, so it spends queries and DML only on the records that need them.
trigger AccountBefore on Account (before update) {
List<Account> changed = new List<Account>();
for (Account a : Trigger.new) {
Account oldAccount = Trigger.oldMap.get(a.Id);
if (a.Industry != oldAccount.Industry) {
changed.add(a);
}
}
if (changed.isEmpty()) {
return;
}
for (Account a : changed) {
a.Description = 'Industry changed to ' + a.Industry;
}
}The early return is allowed in a trigger body, and it avoids running any later queries when nothing relevant changed. Filtering this way reduces CPU time and keeps queries narrow. In a real trigger, the changed list would be the input for the Set, Map and query steps shown above.
Common mistakes
- Reading only the first record. Code such as
Trigger.new[0]handles one record and silently ignores the other 199. Tests that insert a single record will pass. - Assuming a batch of one. Using
Trigger.new.get(0)orTrigger.size == 1checks as a shortcut breaks data loads. - Querying or running DML inside the loop. This is the failure the whole tutorial is built around.
- Using
Trigger.newMapin a before insert trigger. The records have no Ids yet, so the map isnulland the code throws aNullPointerException. - Modifying
Trigger.newin an after trigger. The records are read-only, and the platform raises an error. To change them, query the records again into a new list, then update that list. - Assuming order across batches. Records in a 450-record insert are split into chunks, and the platform does not promise a specific order of invocation beyond the chunks running one after another.
Summary of the working model
- The platform sends records to a trigger in chunks of up to 200, and each chunk is one invocation.
- All chunks of a DML operation, and all triggers they start, share the limits of one transaction.
Trigger.new,Trigger.old,Trigger.newMapandTrigger.oldMaphold the whole batch, and which of them exist depends on the event.- Loops over the batch are fine. Queries and DML statements inside those loops are the risk.
- The standard fix is to collect keys in a Set, query once into a Map, and read from the Map.
Exercise
A Contact trigger runs on before insert. A data load inserts 450 Contacts in a single DML operation. How many times does the trigger run, how many records does each invocation receive, and why does a SOQL query placed inside the for (Contact c : Trigger.new) loop cause a failure?
Show answer
The trigger runs three times, with 200, 200 and 50 records. All three invocations belong to one transaction and share one set of governor limits. A query inside the loop runs once per record, so the first 200-record invocation already uses 200 queries. That passes the synchronous limit of 100, and the transaction fails with a System.LimitException: Too many SOQL queries: 101.
Exercise
You write an after update trigger on Account. You want to find the old Industry value for each updated Account. Which context variable should you use, and why is it better than reading Trigger.old by index?
Show answer
Use Trigger.oldMap and call Trigger.oldMap.get(a.Id) for each Account in Trigger.new. This looks up the old version by Id, so it stays correct without relying on the two lists having matching positions, and it needs no extra loop to match records.