Sub topic 5
Why triggers always receive a list
This chapter assumes you can read basic Apex (classes, loops, collections), know what sObjects are, and can write simple SOQL and DML statements. You should also know that triggers fire on insert, update, delete, and undelete. It builds on the earlier chapters on trigger context variables and governor limits.
A trigger never sees one record
A trigger fires once per group of records, not once per record. Trigger.new is a List<SObject>, and Trigger.oldMap and Trigger.newMap are maps keyed by record ID. The list holds one record when a user saves a single edit. It can hold up to 200 records when the save comes from a larger operation.
The platform splits large operations into chunks of at most 200 records before it runs your trigger. If you insert 450 accounts with one insert statement, your trigger runs three times, with 200, 200, and 50 records. Salesforce treats those three runs as one transaction.
Wait, the diagram must be in the required fence format. Here it is.
Where large batches come from
Many common operations send more than one record to a trigger.
| Source | Why the trigger sees many records |
|---|---|
| Apex DML on a list | `insert accounts;` sends the whole list, up to 10,000 rows per statement. |
| Data Loader and the import wizards | Records are sent in batches and chunked to 200 for triggers. |
| Bulk API and the SOAP and REST APIs | An integration can submit many records in one call. |
| Batch Apex | Each `execute` call can run DML on a list of up to the scope size. |
| Cascading automation | A flow or another trigger can update many related records at once. |
A trigger that only works for one record at a time will pass manual testing in the UI and fail the first time someone runs a data load.
Why the list matters for governor limits
The platform makes the list the unit of work because limits apply to the transaction, not to a chunk or a record. A synchronous transaction allows 100 SOQL queries and 150 DML statements. All trigger runs inside the transaction draw from the same counters.
Suppose a trigger runs one query per record. A save of 1 record uses 1 query. A save of 200 records uses 200 queries and hits the limit of 100. A save of 450 records would fail even sooner, since the queries from chunk 1 are already counted when chunk 2 starts.
Static variables also live for the whole transaction. A static value set during chunk 1 is still there in chunk 2. Later chapters use this for recursion control. Here it lets you observe the chunking directly.
Observing the chunks
This probe records Trigger.size on each invocation. It is a learning tool, so do not deploy it to production.
public class AccountChunkProbe {
public static List<Integer> chunkSizes = new List<Integer>();
}trigger AccountChunkProbeTrigger on Account (before insert) {
AccountChunkProbe.chunkSizes.add(Trigger.size);
}@IsTest
private class AccountChunkProbeTest {
@IsTest
static void splitsLargeInsertIntoChunksOfTwoHundred() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 450; i++) {
accounts.add(new Account(Name = 'Probe ' + i));
}
Test.startTest();
insert accounts;
Test.stopTest();
System.assertEquals(
new List<Integer>{ 200, 200, 50 },
AccountChunkProbe.chunkSizes,
'Expected three trigger invocations'
);
}
}Trigger.size returns the number of records in the current invocation. The test confirms that one insert statement produced three invocations in one transaction.
The single-record mistake
The most common error is treating the list as if it held one record. It usually appears in one of these forms.
trigger AccountTrigger on Account (before insert) {
// Bug: only the first record in the batch is processed
Account acc = Trigger.new[0];
if (acc.Industry == null) {
acc.Industry = 'Other';
}
}With one record this works. With 200 records, 199 of them are silently skipped. No error appears, so the bug can sit in production until a data load exposes it.
The fix is to loop over the list.
trigger AccountTrigger on Account (before insert) {
for (Account acc : Trigger.new) {
if (acc.Industry == null) {
acc.Industry = 'Other';
}
}
}This version is safe because the loop does no SOQL or DML. Looping is necessary but not sufficient. Once the loop body contains a query or a DML statement, you are back to the governor limit problem. The next chapter covers how to remove those.
What you can and cannot assume about a batch
Some properties of a batch are guaranteed, and some are not.
- Size: A batch contains at least 1 record and at most 200 records.
- Order: Records appear in the order submitted, but do not build logic on that order. The same save can come from different sources.
- Mixed content: A batch can contain records that differ in every field. Some may need processing and others may not. Check each record on its own.
- Other batches: You cannot see the other chunks from inside the trigger. If chunk 1 and chunk 2 both need the same related data, each run queries for it separately, unless you cache it in a static variable.
- Failure scope: If any chunk throws an unhandled exception, the whole transaction rolls back, including the chunks that already ran. This applies to an all-or-nothing DML statement. Partial success options are covered in the chapter on error handling.
Because chunks share limits, plan for the whole transaction and not only for 200 records. A trigger that uses 40 queries per invocation is fine for one chunk. For a 450-record insert it uses 120 queries and fails. Most bulkified triggers avoid the problem because they run a fixed number of queries per invocation, such as one, regardless of batch size. With 3 chunks that is 3 queries in total.
Designing for a list from the start
Follow these habits when you begin a new trigger.
- Treat
Trigger.newas a collection. Loop over it, and never index into it by a fixed position. - Write down which queries and DML statements the trigger needs. Each should be able to run once for the whole list.
- Collect the keys first (IDs, names, or other values) into a
Set. Query after the loop with those keys. - Test with 200 records, and also with more than 200 when your logic keeps state between chunks.
Use the Trigger.size probe from this chapter when you are unsure how a particular operation reaches your trigger.
Summary of key points
- A trigger runs once per chunk of up to 200 records, and a larger operation produces several runs.
- All runs in one operation share one transaction, so they share one set of governor limits.
- Code that handles only
Trigger.new[0]skips the remaining records without raising an error. - Looping over the list is required, but queries and DML statements must still stay out of the loop.
Exercise
A user loads 650 contacts with one Data Loader insert, and your Apex trigger on Contact is before insert. How many times does the trigger run, how many records does each run receive, and why can a trigger that runs one SOQL query per record fail even though each run has fewer than 200 records?
Show answer
The trigger runs four times, with 200, 200, 200, and 50 records. All four runs belong to one transaction and share one governor limit counter, so the queries add up across runs. A query per record would need 650 queries in total, and the limit for a synchronous transaction is 100. The failure happens as soon as the count passes 100, which is partway through the first chunk. The fix is to run a fixed number of queries per invocation, regardless of the batch size.