Sub topic 10
Detecting changed fields with oldMap
This chapter assumes you can read basic Apex (loops, List, Set, Map) and that you know what Trigger.new and Trigger.old contain. It also assumes you know the difference between before and after triggers. Here you will learn how to run logic only when a field has actually changed.
Why trigger logic needs change detection
An update trigger fires whenever a record is saved. That includes saves where nothing you care about changed. A user might edit the Phone field, and your trigger still receives the whole record, including StageName.
If you do not compare old and new values, your logic runs on every save. That can overwrite user input, create duplicate follow-up records, or use SOQL and DML you did not need. Change detection means comparing the new version of a record with its prior version and acting only when they differ.
The core pattern
Trigger.oldMap is a Map<Id, SObject>. It is keyed by record Id and holds the version of each record as it was before the save. Trigger.new holds the incoming version. To detect a change, loop over Trigger.new, look up the matching old record by Id, and compare the field.
trigger OpportunityTrigger on Opportunity (before update) {
for (Opportunity opp : Trigger.new) {
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
if (opp.StageName != oldOpp.StageName && opp.StageName == 'Closed Won') {
opp.CloseDate = Date.today();
}
}
}The condition has two parts. The first, opp.StageName != oldOpp.StageName, asks whether the stage changed. The second, opp.StageName == 'Closed Won', asks whether it changed to the value you care about. Without the second part, the trigger would stamp the close date on every stage move. Without the first, it would restamp the date every time someone edited a Closed Won opportunity.
This is a before trigger, so the assignment to opp.CloseDate is saved without any DML statement.
Which events provide oldMap
Trigger.oldMap only exists when there is a prior version of the record to hold. The table shows when it is populated.
| Event | `Trigger.oldMap` |
|---|---|
| before insert, after insert | `null` |
| before update, after update | Populated |
| before delete, after delete | Populated |
| after undelete | `null` |
Comparing fields only makes sense in update events, where both the old and new versions exist. A delete has no new version, and an insert has no old version.
Common error: NullPointerException on insert
Triggers often listen to several events. If one trigger handles both insert and update, Trigger.oldMap is null during an insert. Calling Trigger.oldMap.get(...) then throws a System.NullPointerException.
Guard the lookup with Trigger.isUpdate:
trigger AccountIndustryTrigger on Account (before insert, before update) {
for (Account acc : Trigger.new) {
Account oldAcc = Trigger.isUpdate ? Trigger.oldMap.get(acc.Id) : null;
Boolean industryChanged = oldAcc == null || acc.Industry != oldAcc.Industry;
if (industryChanged && acc.Industry == 'Banking') {
acc.Description = 'Regulated industry: review compliance notes.';
}
}
}Here a new record counts as "changed" because it has no prior value. That choice is a business decision. For some requirements a new record should not count as a change, so write oldAcc != null && acc.Industry != oldAcc.Industry. Decide this explicitly for each requirement.
Comparing several fields
When a requirement involves more than one field, a small helper keeps the loop readable. This example reacts when any of three address fields changes.
public class AccountChangeUtil {
public static Boolean billingAddressChanged(Account newAcc, Account oldAcc) {
return newAcc.BillingStreet != oldAcc.BillingStreet
|| newAcc.BillingCity != oldAcc.BillingCity
|| newAcc.BillingPostalCode != oldAcc.BillingPostalCode;
}
}
trigger AccountAddressTrigger on Account (before update) {
for (Account acc : Trigger.new) {
if (AccountChangeUtil.billingAddressChanged(acc, Trigger.oldMap.get(acc.Id))) {
acc.Description = 'Billing address updated on ' + Date.today().format();
}
}
}Both the class and the trigger are shown in one block for clarity. In an org, save them as two separate files.
Using change detection in after triggers
After triggers are read-only for the records in Trigger.new, so you use change detection to decide which records need follow-up work. The best practice is to gather the relevant records or Ids inside the loop and do the SOQL or DML once, after the loop.
trigger AccountPhoneFollowUp on Account (after update) {
List<Task> tasks = new List<Task>();
for (Account acc : Trigger.new) {
Account oldAcc = Trigger.oldMap.get(acc.Id);
if (acc.Phone != oldAcc.Phone) {
tasks.add(new Task(
Subject = 'Verify updated phone number',
WhatId = acc.Id
));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}If a bulk update touches 200 accounts and only 3 changed phone numbers, this trigger creates 3 tasks with one DML statement. The isEmpty() check avoids issuing a DML statement with nothing to insert.
Edge cases and gotchas
- Before triggers see your own edits. In a before update trigger,
Trigger.newis the live record. If your code modifies a field and then compares it tooldMap, you are comparing your edit, not the user's. Do your comparison before you change the field. oldMapis not affected by your changes. Values inTrigger.oldMapstay as they were before the save, even if you modifyTrigger.new.- String comparison is case-insensitive. In Apex,
==and!=ignore case for strings. A change from'acme'to'ACME'is not detected. If case matters, use===and!==, which compare exactly. - Null values compare safely.
null != 'Open'evaluates totrue, andnull != nullisfalse. You do not need extra null checks for plain equality tests. You do need them before calling methods on a value, such asacc.Name.toLowerCase(). - Loop through
Trigger.new, notoldMap. Iterate overTrigger.newand look up the old record. That way each iteration has both versions. - Re-fired triggers. If your after trigger updates the same object, the trigger runs again, and the second run sees a different old version. The next chapters cover recursion control, but note now that change detection alone does not stop recursion if your own update changes the watched field.
- Other automation can change values. Field updates from workflow rules or flows can cause the trigger to fire again in the same transaction. Each run gets its own
oldMapreflecting the state before that run.
Testing change detection
Write at least these cases for any change-detecting trigger:
- Update a record without touching the watched field. The logic must not run.
- Update the watched field to the target value. The logic must run.
- Update the watched field to a different, non-target value. The logic must not run.
- Update 200 records in one DML statement. The trigger must stay within governor limits.
Exercise
A trigger on Account is declared with (before insert, before update). It contains the line Account oldAcc = Trigger.oldMap.get(acc.Id); inside a loop over Trigger.new. What happens when a user creates a new Account, and how do you fix it?
Show answer
Trigger.oldMap is null during insert, so the call throws a NullPointerException and the save fails. Fix it by checking the event first, for example Account oldAcc = Trigger.isUpdate ? Trigger.oldMap.get(acc.Id) : null;, and then handle the null case in the comparison.
Exercise
In an after update trigger on Opportunity, you want to create one Task for each opportunity whose Amount changed. Describe how you would structure the loop and where the DML statement goes.
Show answer
Loop over Trigger.new, get the old record with Trigger.oldMap.get(opp.Id), and compare opp.Amount to oldOpp.Amount. When they differ, add a new Task (with WhatId set to opp.Id) to a List<Task>. After the loop, insert the list once, ideally only if it is not empty. This keeps the trigger bulk-safe with one DML statement.