Sub topic 12
Writing Triggers That Handle Up to 200 Records Per Batch
This chapter assumes you know basic Apex syntax (loops, List, Set, Map), SOQL and DML statements, and the idea of governor limits. It builds on Trigger.new, Trigger.old and their map versions.
Why triggers must be bulk-safe
A trigger does not run once per record. Salesforce hands the trigger a batch. A single DML statement, a data import, an API call or a Data Loader job can pass many records at once. Salesforce splits large operations into chunks of up to 200 records, and the trigger runs once for each chunk.
So Trigger.new is a list that can hold anywhere from 1 to 200 records. A trigger that only works when the list holds one record is a bug waiting for the first data load.
The cost shows up in governor limits. These per-transaction limits matter most here:
| Limit | Synchronous value |
|---|---|
| SOQL queries issued | 100 |
| DML statements issued | 150 |
| Records retrieved by SOQL | 50,000 |
| Records processed by DML | 10,000 |
A trigger that runs one query per record uses 200 of the 100 allowed queries on a full chunk. It fails with a System.LimitException, and the whole transaction rolls back.
The rule: no SOQL or DML inside a loop
Bulk-safe triggers follow one pattern:
- Loop over
Trigger.newto collect the Ids or values you need into aSetorList. - Run one SOQL query outside the loop, using
IN :collection. - Put the results in a
Mapfor fast lookup. - Loop again to apply logic, using the map instead of querying.
- Collect records to change in a
Listand run one DML statement after the loop.
The next sections show each step.
Anti-pattern: a query inside the loop
This trigger copies the parent account's industry onto each new contact's description. It looks correct, and it works for one record.
trigger ContactIndustryBad on Contact (before insert) {
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
// One query per contact: fails at 101 records
Account a = [SELECT Industry FROM Account WHERE Id = :c.AccountId];
c.Description = 'Industry: ' + a.Industry;
}
}
}With 101 contacts in one chunk, the 101st query throws a limit exception. The same failure happens with a insert or update statement inside a loop, only against the DML limit.
The bulk-safe version
trigger ContactIndustry on Contact (before insert) {
// Step 1: collect parent Ids
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
// Step 2 and 3: one query, results in a map
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
// Step 4: apply logic using the map
for (Contact c : Trigger.new) {
Account a = accountsById.get(c.AccountId);
if (a != null) {
c.Description = 'Industry: ' + a.Industry;
}
}
}This trigger uses one query whether the chunk holds 1 record or 200. Three details are worth noting:
- A
Setremoves duplicates, so 200 contacts for the same account produce one Id. new Map<Id, SObject>(list)builds a map keyed by record Id in a single expression.accountsById.get(null)returnsnulland does not throw, but the explicit null checks make the intent clear. Always handle the case where a lookup finds nothing.
Bulk-safe DML in after triggers
In an after trigger you often create or update related records. Collect them first, then run one DML statement. This trigger creates one task for each new opportunity that is large enough to need follow-up.
trigger OpportunityFollowUp on Opportunity (after insert) {
List<Task> tasks = new List<Task>();
for (Opportunity opp : Trigger.new) {
if (opp.Amount != null && opp.Amount > 50000) {
tasks.add(new Task(
Subject = 'Review large opportunity',
WhatId = opp.Id
));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}The isEmpty() check is optional, since inserting an empty list is allowed. However, an empty insert still counts as a DML statement in some cases, and the check keeps the intent explicit.
Aggregating child data in bulk
A common need is to update parent records based on children. Use one aggregate query grouped by parent, not one query per parent. This trigger writes the count of contacts onto each affected account.
trigger ContactCountSync on Contact (after insert, after delete, after undelete) {
List<Contact> source = Trigger.isDelete ? Trigger.old : Trigger.new;
Set<Id> accountIds = new Set<Id>();
for (Contact c : source) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
if (accountIds.isEmpty()) {
return;
}
Map<Id, Integer> counts = new Map<Id, Integer>();
for (Id accId : accountIds) {
counts.put(accId, 0);
}
for (AggregateResult ar : [
SELECT AccountId acc, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
]) {
counts.put((Id) ar.get('acc'), (Integer) ar.get('total'));
}
List<Account> toUpdate = new List<Account>();
for (Id accId : counts.keySet()) {
toUpdate.add(new Account(
Id = accId,
NumberOfEmployees = counts.get(accId)
));
}
update toUpdate;
}Points to notice:
- The trigger reads
Trigger.oldon delete, becauseTrigger.newis null for that event. - Every account starts at a count of 0. An account whose last contact was deleted returns no row from the aggregate query, and without the default it would keep a stale count.
- The
forloop over the query results iterates the rows, but the query itself runs once. - The example writes to the standard
NumberOfEmployeesfield only so the code runs in any org. In real work you would use a custom field.
Edge cases to plan for
- Partial batches. The final chunk of a large job can hold fewer than 200 records. Never assume a fixed size.
- Mixed data. Within one batch, some records have a null lookup, some change a field and some do not. Handle each case inside the loop.
- Multiple chunks per transaction. Limits apply to the whole transaction, not to each chunk. When a job processes several chunks in one transaction, the limit counters keep accumulating, so a trigger that uses 40 queries per chunk can still fail on the third chunk.
- Query size. A single query cannot return more than 50,000 records in total for the transaction. Filter with
WHEREclauses and select only the fields you need. - Map keys. When you key a map by something other than Id, such as an email address, two records in the batch can share a key. Decide what should happen for duplicates.
- Order inside the batch. Do not rely on records appearing in any particular order within
Trigger.new.
A quick test for bulk safety
Write a test that inserts 200 records in one DML statement and checks the result.
@isTest
private class ContactIndustryTest {
@isTest
static void handlesFullBatch() {
Account acc = new Account(Name = 'Bulk Test', Industry = 'Energy');
insert acc;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'Test ' + i, AccountId = acc.Id));
}
Test.startTest();
insert contacts;
Test.stopTest();
List<Contact> saved = [SELECT Description FROM Contact WHERE AccountId = :acc.Id];
System.assertEquals(200, saved.size());
for (Contact c : saved) {
System.assertEquals('Industry: Energy', c.Description);
}
}
}If the trigger queried inside the loop, this test would fail with a limit exception. That makes it a useful guard against regressions.
Common mistakes
- Reading only
Trigger.new[0], which silently ignores 199 records. - Calling a helper method that runs a query, from inside a loop. The query hides behind the method call but still counts.
- Building a query string with record values concatenated in, instead of using bind variables with
IN :set. - Updating the records in
Trigger.newwith DML inside an after trigger. Those records are read-only there, so create newSObjectinstances with the Id set, or use a before trigger.
Exercise
A before update trigger on Case runs [SELECT Id, Email FROM Contact WHERE Id = :c.ContactId] inside for (Case c : Trigger.new). A user updates 150 cases in one operation. What happens, and how do you fix it?
Show answer
The trigger issues 150 queries, which exceeds the limit of 100 SOQL queries per transaction, so a System.LimitException is thrown and the whole transaction rolls back. To fix it, first loop over Trigger.new and add each non-null ContactId to a Set<Id>. Then run one query with WHERE Id IN :contactIds and store the results in a Map<Id, Contact>. Finally, loop again and read the contact from the map.
Exercise
In the ContactCountSync trigger, why is every account Id put into the counts map with a value of 0 before the aggregate query runs?
Show answer
An aggregate query with GROUP BY returns a row only for accounts that still have at least one contact. If the last contact of an account was deleted, no row comes back for it. Without the default of 0, that account would not be updated and would keep its old, incorrect count.