Sub topic 5
Run logic only when a field actually changed
This chapter assumes you can write a basic Apex trigger, use List, Set and Map, and understand DML statements such as update. It also assumes you know the governor limits at a high level. You should recognize Trigger.new, Trigger.old and Trigger.oldMap from the earlier chapters on trigger context.
Why a changed-field check helps
A trigger that updates its own object can cause the trigger to run again. The earlier chapters on how recursion occurs showed the cause. An after update trigger issues DML on the same records, and that DML fires the trigger again.
Many triggers don't need to run on every update. They care about one or two fields. A trigger that recalculates something when Rating changes has no reason to do work when only Phone changed.
A changed-field check compares the new value of a field with its old value. If the two match, the record is skipped. This does two things:
- It reduces work, because unrelated updates do nothing.
- It can end a recursive chain. When the re-fired trigger sees that the watched field did not change, it does nothing, and the chain stops.
This is a filter on which records the logic applies to. It is not a general recursion guard, and the limits below matter.
Comparing new and old values
On update, Salesforce gives you two views of each record:
Trigger.newis a list of the records with their new values.Trigger.oldMapis a map from record Id to the record as it was before the update.
Look up the old record by Id, then compare the field.
public class AccountRatingHandler {
public static void afterUpdate(List<Account> newList, Map<Id, Account> oldMap) {
List<Account> changed = new List<Account>();
for (Account acc : newList) {
Account oldAcc = oldMap.get(acc.Id);
if (acc.Rating != oldAcc.Rating) {
changed.add(acc);
}
}
if (changed.isEmpty()) {
return;
}
// process only the records in 'changed'
}
}The trigger passes both collections to the handler:
trigger AccountTrigger on Account (after update) {
if (Trigger.isAfter && Trigger.isUpdate) {
AccountRatingHandler.afterUpdate(Trigger.new, Trigger.oldMap);
}
}The early return when changed is empty avoids running DML or queries for nothing. That matters for governor limits as well as clarity.
Where the old values exist
Trigger.oldMap and Trigger.old exist only for update and delete events. They are null on insert. Calling oldMap.get(...) in an insert context throws a NullPointerException.
| Event | `Trigger.new` | `Trigger.oldMap` |
|---|---|---|
| before insert | Available, can be modified | `null` |
| after insert | Available, read-only | `null` |
| before update | Available, can be modified | Available |
| after update | Available, read-only | Available |
| before delete | `null` | Available |
| after delete | `null` | Available |
| after undelete | Available, read-only | `null` |
If your handler serves both insert and update, check Trigger.isInsert or test oldMap != null before comparing. On insert, a common rule is to treat any non-null value as a change.
public static Boolean ratingChanged(Account acc, Map<Id, Account> oldMap) {
if (oldMap == null || !oldMap.containsKey(acc.Id)) {
return acc.Rating != null; // insert: treat a set value as a change
}
return acc.Rating != oldMap.get(acc.Id).Rating;
}Checking several fields
Often the logic depends on more than one field. Compare each one, or put the fields in a list and loop over them.
public class AccountChangeDetector {
private static final List<Schema.SObjectField> WATCHED = new List<Schema.SObjectField>{
Account.Rating,
Account.Industry,
Account.OwnerId
};
public static Boolean hasWatchedChange(Account newAcc, Account oldAcc) {
for (Schema.SObjectField f : WATCHED) {
if (newAcc.get(f) != oldAcc.get(f)) {
return true;
}
}
return false;
}
}SObject.get(field) returns an Object. The != operator compares values for the types you commonly watch: strings, numbers, dates, Ids and picklist values. Keep the watched list short and specific. A list of every field defeats the purpose.
A changed-field check is not a full guard
The check limits recursion only when the re-fired trigger sees no relevant change. Consider this handler:
public class RatingEscalationHandler {
public static void afterUpdate(List<Account> newList, Map<Id, Account> oldMap) {
List<Account> toUpdate = new List<Account>();
for (Account acc : newList) {
if (acc.Rating != oldMap.get(acc.Id).Rating) {
toUpdate.add(new Account(Id = acc.Id, Rating = 'Hot'));
}
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}
}Suppose a user changes Rating from Cold to Warm. The trigger sees a change and sets Rating to Hot. That update changes Rating again, from Warm to Hot, so the trigger runs a second time. This time the handler sees a change again and sets Rating to Hot. The new value equals the current one, so the third pass sees no change and stops.
That chain ends, but only because the logic converges: writing the same value twice produces no change. If the handler wrote a different value each time, such as a counter or a timestamp, the check would never see "no change", and recursion would continue until the depth limit.
The rule: a changed-field check ends recursion only when the field your trigger writes is not the field it watches, or when the written value is stable.
The safest pattern is to watch one field and write a different one.
if (acc.Rating != oldMap.get(acc.Id).Rating) {
toUpdate.add(new Account(Id = acc.Id, Description = 'Reviewed'));
}Here the trigger writes Description. The second pass sees that Rating did not change and does nothing.
Edge cases
Workflow field updates and re-fired triggers
Some automation, such as a workflow field update, can cause the before and after triggers to run a second time in the same transaction. On that second run, Trigger.oldMap holds the values from before the workflow's update, not the original values from the user's save. A changed-field check can therefore still report a change on the second run.
Don't rely on the check to run logic exactly once in this situation. If the logic must run once per record, combine the check with a static Set<Id> guard, covered in later chapters.
Null values
Comparing with != handles null safely in Apex. null != 'Hot' is true, and null != null is false. You don't need extra null checks for a simple comparison. You do need them when calling methods on the value, such as acc.Name.toLowerCase().
Formula fields and system fields
Formula fields are calculated and are not reliable to compare in a before context, because their values reflect the saved record. LastModifiedDate and SystemModstamp change on every save, so watching them makes the check always true.
Case sensitivity
String != in Apex is case-insensitive. A change from hot to HOT is not detected. If case matters, use !acc.Name.equals(oldAcc.Name), which is case-sensitive.
String a = 'hot';
String b = 'HOT';
System.debug(a != b); // false: the comparison ignores case
System.debug(!a.equals(b)); // true: equals() is case-sensitiveMulti-select picklists
A multi-select picklist is stored as a semicolon-separated string. Selecting the same values in a different order can produce a different string. If order doesn't matter, split both strings and compare them as sets.
Combining with other guards
The changed-field check works well as the first filter. A typical handler layers the guards:
- Return early if the event is not one the handler cares about.
- Filter to records where the watched fields changed.
- Skip Ids already processed, using the static
Set<Id>from a later chapter. - Do the work, then add the Ids to the set.
The changed-field check removes most unneeded work cheaply. The Id set protects against the cases the check can't catch.
Common errors
- Calling
oldMap.get(...)on insert, which throwsNullPointerException. - Watching and writing the same field with a changing value, such as a counter.
- Watching too many fields, so almost every update counts as a change.
- Comparing
acc.RatingwithTrigger.newof the same record instead of the old record, which always matches. - Assuming the check guarantees one run per record when workflow updates are involved.
Exercise
An after update trigger on Account sets NumberOfEmployees = acc.NumberOfEmployees + 1 for records where NumberOfEmployees changed. Why does a changed-field check on NumberOfEmployees fail to stop recursion, and what is one fix?
Show answer
The trigger writes the same field it watches, and the written value is different each time. Every pass sees a changed NumberOfEmployees and adds one again, so recursion continues until the depth limit. Fixes include watching a different field than the one written, moving the change into a before trigger so no extra DML runs, or adding a static Set<Id> guard so each record is processed once.
Exercise
A handler serves both before insert and before update and calls oldMap.get(acc.Id).Industry. What happens on insert, and how do you fix it?
Show answer
Trigger.oldMap is null on insert, so the call throws a NullPointerException. Check oldMap == null (or Trigger.isInsert) first, and on insert treat a non-null Industry as a change.