Advanced 35 min read

Build Bulk-Safe Transaction Triggers

By the end of this lesson, you'll be able to:

  • Write a trigger that updates Bank_Account__c.Balance__c when a Transaction__c is inserted
  • Handle a bulk insert of transactions across many different accounts correctly
  • Reuse Module 26's exact rollup-trigger pattern in a higher-stakes context

Prerequisites: "Design the Account Model"

Grouping by account, not looping per record

trigger TransactionTrigger on Transaction__c (after insert) {
    Map<Id, Decimal> deltaByAccount = new Map<Id, Decimal>();

    for (Transaction__c t : Trigger.new) {
        Decimal delta = (t.Type__c == 'Withdrawal') ? -t.Amount__c : t.Amount__c;
        deltaByAccount.put(
            t.Bank_Account__c,
            (deltaByAccount.get(t.Bank_Account__c) ?? 0) + delta
        );
    }

    List<Bank_Account__c> toUpdate = new List<Bank_Account__c>();
    for (Bank_Account__c acc : [SELECT Id, Balance__c FROM Bank_Account__c WHERE Id IN :deltaByAccount.keySet()]) {
        acc.Balance__c += deltaByAccount.get(acc.Id);
        toUpdate.add(acc);
    }
    update toUpdate;
}

This is Module 26's exact rollup-trigger shape: one map built in a single loop over Trigger.new, one query, one DML statement — regardless of whether 1 or 200 transactions arrive together, exactly the bulk-safety discipline from Module 25.

Deposits add, withdrawals subtract

The delta calculation — negative for a withdrawal, positive for a deposit — means a single account with multiple transactions of different types in the same bulk insert still nets out correctly, since the map accumulates the sum of deltas per account, not just the count of transactions.

What this trigger deliberately does NOT do yet

This trigger doesn't check whether a withdrawal would make Balance__c negative, or whether the account's Status__c allows transactions at all — those are validation concerns, and Module 24's separation of trigger logic from validation logic means they belong in a dedicated place, covered next.

Exercise

As a comment, explain what would go wrong if this trigger updated each Bank_Account__c inside the loop over Trigger.new, one at a time, instead of grouping deltas into a map first.

Show hint

Think about what happens with 200 transactions across only 5 accounts.

APEX

Build Bulk-Safe Transaction Triggers Quiz

1. Why does the trigger build a Map<Id, Decimal> of deltas before querying or updating any accounts?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

The balance-update trigger reuses Module 26's bulk-safe rollup pattern precisely — grouping transactions by account, summing once per account, and updating in a single DML statement, regardless of how many transactions arrive in one batch.