Sub topic 10
Acting only on records that changed
This chapter assumes you can read Trigger.new, Trigger.old, Trigger.oldMap, and the context flags such as Trigger.isInsert. It also assumes you know that a trigger always receives a list of records.
Why filter on changes
An update trigger fires when any field on a record is saved, even a field you don't care about. If your logic creates tasks, runs queries, or calls other systems, running it for every saved record wastes limits. It can also repeat side effects, such as creating a second welcome task each time an already-won opportunity is edited.
To avoid this, compare each record's new values with its old values. Act only when the field you care about has changed.
Comparing new and old values
Trigger.oldMap maps record IDs to the values the records had before the DML. Use the ID of each record in Trigger.new to find its old version.
Availability depends on the context:
| Context | `Trigger.new` | `Trigger.oldMap` |
|---|---|---|
| before insert | Available, records have no Id yet | null |
| after insert | Available, records have Ids | null |
| before update, after update | Available | Available |
| before delete, after delete | null | Available |
Calling oldMap.get(...) during an insert throws a NullPointerException. Always check for null first, or check Trigger.isUpdate.
public with sharing class ChangeDetector {
public static Boolean hasChanged(
SObject newRec,
Map<Id, SObject> oldMap,
Schema.SObjectField field
) {
// On insert there is no old version, so treat the value as new.
if (oldMap == null) {
return true;
}
SObject oldRec = oldMap.get(newRec.Id);
if (oldRec == null) {
return true;
}
return newRec.get(field) != oldRec.get(field);
}
}Use the helper in a handler. The loop below collects only the opportunities whose StageName changed, so later queries and DML work on a smaller list.
public with sharing class OpportunityStageHandler {
public static void handle(
List<Opportunity> newOpps,
Map<Id, Opportunity> oldMap
) {
List<Opportunity> changed = new List<Opportunity>();
for (Opportunity opp : newOpps) {
if (ChangeDetector.hasChanged(opp, oldMap, Opportunity.StageName)) {
changed.add(opp);
}
}
if (changed.isEmpty()) {
return;
}
// Run bulk queries and DML on "changed" only.
}
}The loop contains no SOQL or DML. It only reads values already in memory, so the cost is the same for 1 record or 200.
Common mistakes
- Comparing
Trigger.newtoTrigger.oldby list position. The two lists are not guaranteed to match. Look records up by ID inTrigger.oldMap. - Checking
isWonbut notwasWon. A record already in the target state passes the check on every later save. - Looking up old values in a before insert trigger by
Id. TheIdis still null there, andoldMapis null anyway. - Writing a field in a trigger and then expecting the comparison to see the original value. In a before trigger, your own changes to
Trigger.newrecords are the new values.
Exercise
A before update trigger on Case must set a Escalated_Date__c field when Priority changes to 'High'. Which two conditions should the loop check for each record, and why must the loop use Trigger.oldMap and not Trigger.old?
Show answer
Check that the new Priority equals 'High' and that the old Priority, read from Trigger.oldMap.get(c.Id), was not 'High'. This stops the date from being reset on later saves of an already-high case. Trigger.oldMap gives lookup by ID, so you don't depend on the position of records in two separate lists.