Apex
Bulk-safe triggers, from the start
Process collections, keep queries out of loops, and understand before versus after triggers.
By Vishal Verma · Reviewed October 5, 2026
A trigger may receive many records in one execution. Write logic for the entire collection, even when your first test uses one record.
- Use a before trigger to change fields on the records being saved. You do not need extra DML for those changes.
- Collect IDs in a Set and query related records once, outside the loop.
- Use a Map to match related data and accumulate changes in a List.
- Perform required DML on the collection after the loop.
- Test one record, a batch of records, and cases with missing related data.
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]
);This snippet collects related accounts. Add your business logic and suitable tests before using it in a project.