GSalesforceGyan
← Browse learning guides

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.

  1. Use a before trigger to change fields on the records being saved. You do not need extra DML for those changes.
  2. Collect IDs in a Set and query related records once, outside the loop.
  3. Use a Map to match related data and accumulate changes in a List.
  4. Perform required DML on the collection after the loop.
  5. 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.

Official reference

Read the Salesforce documentation or Trailhead resource