Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Triggers

Bulkification in Triggers

Learn to bulkify Apex triggers so they handle 200 records safely: collect Ids, query once, group with maps, update in bulk, with runnable Java stand-ins.

A trigger is called once per batch of records, not once per record. When a user edits one Account, the batch has one record. When an admin uploads a file of 10,000 accounts, Salesforce calls the trigger in chunks of up to 200. A trigger that works for one record but fails for 200 is the most common Apex bug in the wild. Bulkification means writing code so it handles any number of records with a fixed number of queries and DML statements.

The real trigger code below is read-only; the Java stand-ins count "queries" the way the platform does, so you can see the difference between the bad and good versions.

The un-bulkified trigger

Java
trigger OpportunityTrigger on Opportunity (after insert) {
    for (Opportunity opp : Trigger.new) {
        // BAD: query in a loop
        Account acc = [SELECT Id, Name FROM Account WHERE Id = :opp.AccountId];
        acc.Description = 'Has new opportunity';
        // BAD: DML in a loop
        update acc;
    }
}

With 1 record this uses 1 query and 1 DML. With 200 records it uses 200 of each, and the transaction dies at the 101st query. The trigger passed testing with a single record and then failed in production on a data load.

The bulkified recipe

Follow four steps every time:

  1. Collect the keys you need (Ids) into a Set while looping once over Trigger.new.
  2. Query once, outside the loop, using IN :ids.
  3. Index the results in a Map so lookups cost nothing.
  4. Collect changed records into a list and run one DML after the loop.
Java
trigger OpportunityTrigger on Opportunity (after insert) {
    // 1. collect
    Set<Id> accountIds = new Set<Id>();
    for (Opportunity opp : Trigger.new) {
        if (opp.AccountId != null) {
            accountIds.add(opp.AccountId);
        }
    }

    // 2 + 3. query once and index
    Map<Id, Account> accounts = new Map<Id, Account>(
        [SELECT Id, Description FROM Account WHERE Id IN :accountIds]
    );

    // 4. modify, then one DML
    List<Account> toUpdate = new List<Account>();
    for (Opportunity opp : Trigger.new) {
        Account acc = accounts.get(opp.AccountId);
        if (acc != null) {
            acc.Description = 'Has new opportunity';
            toUpdate.add(acc);
        }
    }
    update toUpdate;
}

Two loops over Trigger.new, one query, one DML: for 1 record or 200. Note the Map handles a subtle point: if two opportunities share an Account, the map returns the same object, so the account is edited twice but updated once. (If an Account appears twice in toUpdate, Salesforce raises "Duplicate id in list". Use a Map<Id, Account> for the update list, or a Set, when duplicates are possible.)

flowchart LR
    A["Loop 1:<br/>collect AccountIds"] --> B["ONE query<br/>WHERE Id IN :ids"]
    B --> C["Map Id to Account"]
    C --> D["Loop 2:<br/>edit via map"]
    D --> E["ONE update"]

Each pass touches the whole batch; the database is only visited twice.

Counting the cost with a stand-in

This Java model charges one "query" per database call. Compare how many each version uses for 200 opportunities, with a budget of 100.

Java Stand-in (Java): bad versus bulkified trigger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Roll-up from children to a parent

A very common trigger task is a roll-up: "keep Account.Open_Opportunity_Count__c correct". The bulk-safe approach uses an aggregate query grouped by parent, then one update:

Java
trigger OpportunityRollup on Opportunity (after insert, after update, after delete, after undelete) {
    Set<Id> accountIds = new Set<Id>();
    List<Opportunity> records = Trigger.isDelete ? Trigger.old : Trigger.new;
    for (Opportunity o : records) {
        if (o.AccountId != null) accountIds.add(o.AccountId);
    }

    Map<Id, Integer> counts = new Map<Id, Integer>();
    for (AggregateResult ar : [SELECT AccountId a, COUNT(Id) c FROM Opportunity
                               WHERE AccountId IN :accountIds AND IsClosed = false
                               GROUP BY AccountId]) {
        counts.put((Id) ar.get('a'), (Integer) ar.get('c'));
    }

    List<Account> toUpdate = new List<Account>();
    for (Id accId : accountIds) {
        toUpdate.add(new Account(Id = accId, Open_Opportunity_Count__c = counts.containsKey(accId) ? counts.get(accId) : 0));
    }
    update toUpdate;
}

Two details matter: accounts with no open opportunities do not appear in the aggregate results, so the code defaults them to 0; and delete triggers use Trigger.old.

The stand-in below mimics a roll-up with a grouped count.

Java Stand-in (Java): roll-up with a grouped count

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Testing for bulk

Always test triggers with 200 records at once (and in the test, also test 1 record and a mix). A trigger that passes only on one record has not been tested. Chapter 5 covers writing Apex tests.

Bulkification checklist

  • No SOQL or DML inside a for loop.
  • Use Set<Id> for collected keys, Map<Id, SObject> for lookups.
  • Use IN :set in the WHERE clause.
  • Update with a single list after the loop; avoid duplicate Ids in that list.
  • Do not assume Trigger.new has one record.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the maximum batch of records a trigger receives in one call?

    Records are handed to triggers in chunks of up to 200, so code must handle that many at once.
  2. 2. Where should the SOQL query be placed in a bulkified trigger?

    One query outside the loop, filtering with IN :ids, costs one query for any number of records.
  3. 3. Why use a Map<Id, Account> after the query?

    A map gives constant-time lookups from the Id on each trigger record to its queried parent.
  4. 4. Why might an Account appear in the update list twice and cause an error?

    Adding the same record Id twice to one update list causes a duplicate Id error. Use a Map keyed by Id to hold records to update.

Summary

  • Triggers receive up to 200 records per call; write them to handle that many.
  • Never put SOQL or DML inside a loop.
  • Collect Ids, query once with IN, index with a map, and update once.
  • Roll-ups use grouped aggregate queries and must default missing groups to zero.
  • Test with 200 records.

Next: The Trigger Handler Pattern