Sub topic 10
Acting only on records that changed
This chapter assumes you can write Apex classes and triggers, run basic SOQL and DML, and already know that a trigger receives a list of up to 200 records. It also assumes you know the earlier patterns for collecting IDs in a Set and looking up query results in a Map.
Why filter on changes
An update trigger fires whenever a record is saved, whether or not a field you care about changed. A user may edit a phone number, a flow may stamp a date, or an integration may re-save 200 records with identical values. If your trigger queries related records and runs DML for every one of those saves, you spend governor limits and database time on nothing.
Change detection means comparing each record's new field values with its old values and doing the expensive work only for records that differ. It has two benefits:
- It cuts the number of records that go into your queries and DML statements.
- It often lets you skip the query or DML entirely, because the filtered collection is empty.
Where the old values come from
Salesforce supplies the previous values in the trigger context variables. Which ones are populated depends on the operation.
| Variable | before insert | after insert | before update | after update |
|---|---|---|---|---|
| `Trigger.new` | Yes, writable, no Id yet | Yes, read-only | Yes, writable | Yes, read-only |
| `Trigger.newMap` | null | Yes | Yes | Yes |
| `Trigger.old` | null | null | Yes | Yes |
| `Trigger.oldMap` | null | null | Yes | Yes |
On insert there is no previous version, so Trigger.oldMap is null. Calling Trigger.oldMap.get(...) in a trigger that also handles insert throws a NullPointerException. Check Trigger.isUpdate or compare Trigger.oldMap with null before you read it.
Trigger.oldMap is keyed by record Id, which is the right structure here. Looking up the old version of a record is a Map access, not a loop over Trigger.old, so it costs no queries and stays fast at 200 records.
The basic comparison
The simplest form compares one field inside the loop. This version runs in a before trigger and handles both insert and update:
trigger OpportunityTrigger on Opportunity (before insert, before update) {
for (Opportunity opp : Trigger.new) {
Boolean stageChanged = Trigger.isInsert
|| opp.StageName != Trigger.oldMap.get(opp.Id).StageName;
if (stageChanged) {
opp.Description = 'Stage is now ' + opp.StageName;
}
}
}The || operator short-circuits. On insert, Trigger.isInsert is true, so the right side never runs and the null oldMap is never touched. On update, the right side runs once per record, with no SOQL involved.
This is a design choice: the code treats an insert as a change. That is usually right, because a new record has "changed" from nothing to its first value. If your rule should apply only when a value moves from one real value to another, test Trigger.isUpdate instead.
A reusable helper
Comparing several fields across several triggers repeats the same null checks. A small helper keeps them in one place. SObject.get accepts a Schema.SObjectField token, so the field is checked at compile time and you avoid string field names.
public with sharing class ChangeDetector {
// Returns true for inserts (oldRec is null) or when the field value differs.
public static Boolean hasChanged(
SObject newRec,
SObject oldRec,
Schema.SObjectField field
) {
if (oldRec == null) {
return true;
}
return newRec.get(field) != oldRec.get(field);
}
public static Boolean anyChanged(
SObject newRec,
SObject oldRec,
List<Schema.SObjectField> fields
) {
for (Schema.SObjectField field : fields) {
if (hasChanged(newRec, oldRec, field)) {
return true;
}
}
return false;
}
}The helper performs no queries or DML, so calling it inside a loop is safe.
Filtering before you query
The main payoff comes when change detection feeds a bulk query. Collect only the IDs of records that changed. If none did, return before touching the database.
public with sharing class OpportunityStageHandler {
public static void flagAccounts(
List<Opportunity> newOpps,
Map<Id, Opportunity> oldMap
) {
Set<Id> accountIds = new Set<Id>();
for (Opportunity opp : newOpps) {
Opportunity oldOpp = oldMap == null ? null : oldMap.get(opp.Id);
if (opp.AccountId != null
&& ChangeDetector.hasChanged(opp, oldOpp, Opportunity.StageName)) {
accountIds.add(opp.AccountId);
}
}
if (accountIds.isEmpty()) {
return;
}
List<Account> accounts = [
SELECT Id, Description
FROM Account
WHERE Id IN :accountIds
];
for (Account acct : accounts) {
acct.Description = 'Opportunity stage changed on '
+ Datetime.now().format();
}
update accounts;
}
}Consider a batch of 200 opportunities where only 3 changed stage. The trigger runs one query for at most 3 accounts and one update of those accounts. The 197 unchanged records cost nothing. If no stage changed, no query runs at all.
The Set<Id> also removes duplicates. Ten changed opportunities on the same account produce one account in the update, which avoids a "duplicate id in list" error that a List could trigger.
Gotchas
Null handling
!= in Apex compares values, and a null on one side is fine. null != 'Closed Won' is true and no exception occurs. The risk is the oldMap or the old record being null, not the field value. Guard the record, not the field.
String case
For String values, == and != ignore case. Changing 'acme' to 'ACME' does not register as a change. If capitalization matters, compare with a.equals(b). That method throws on a null receiver, so check for null first.
Old values are a snapshot
Trigger.oldMap holds the values from the database at the start of the save. In a before update trigger, another before trigger or your own code may already have modified Trigger.new. Your comparison sees those modified values against the original ones. That is usually what you want, because it reflects what is about to be saved.
Formula and system fields
Formula fields are calculated after the before triggers. In a before update trigger, a formula field on Trigger.new still holds its old value, so comparing it tells you nothing. Compare the source fields the formula depends on instead.
Re-fired updates
A workflow field update on the same record can cause the trigger to fire a second time within the same transaction. On that second run, Trigger.oldMap holds the values from just before the field update, not the values at the start of the transaction. If your logic must run once per transaction, rely on the recursion guard covered later in this tutorial.
Testing a partial change
Verify that the filter works by changing only some records in a batch. This test updates 50 of 200 opportunities and expects the helper to report exactly 50 changes.
@IsTest
private class ChangeDetectorTest {
@IsTest
static void detectsOnlyChangedRecords() {
List<Opportunity> before = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
before.add(new Opportunity(
Name = 'Opp ' + i,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
));
}
insert before;
List<Opportunity> after = [
SELECT Id, StageName FROM Opportunity WHERE Id IN :before
];
Map<Id, Opportunity> oldMap = new Map<Id, Opportunity>(
[SELECT Id, StageName FROM Opportunity WHERE Id IN :before]
);
for (Integer i = 0; i < 50; i++) {
after[i].StageName = 'Qualification';
}
Integer changed = 0;
for (Opportunity opp : after) {
if (ChangeDetector.hasChanged(
opp, oldMap.get(opp.Id), Opportunity.StageName)) {
changed++;
}
}
System.assertEquals(50, changed, 'Only the 50 edited records should count');
}
}The second query builds oldMap as an independent copy, so edits to after do not alter it. Because the stage values were never saved, the test needs no DML for the update.
Summary of the pattern
- Read
Trigger.newand, for updates,Trigger.oldMap. - Decide how inserts count, and guard against a null
oldMap. - Compare only the fields your logic depends on.
- Collect changed records or their IDs into a Set or List.
- Return early if the collection is empty.
- Run one query and one DML statement on what remains.
Exercise
A trigger on Contact is declared for before insert, before update. It contains the line if (c.Email != Trigger.oldMap.get(c.Id).Email) { ... }. It works when users edit contacts but fails when contacts are imported. Why, and how do you fix it?
Show answer
On insert, Trigger.oldMap is null, so calling get on it throws a NullPointerException. Fix it by checking the context first, for example Trigger.isInsert || c.Email != Trigger.oldMap.get(c.Id).Email, or by passing Trigger.oldMap to a helper that treats a null map or null old record as "changed".
Exercise
A handler receives 200 opportunities and queries accounts for all of their AccountIds, then updates every account. Only the Amount field is relevant to the logic, and usually 1 or 2 opportunities per batch change Amount. Describe the change that reduces query and DML work, and say what happens when no Amount changed.
Show answer
Compare opp.Amount with the value in oldMap inside the loop and add opp.AccountId to a Set only for opportunities where Amount changed. Query and update only the accounts in that Set. When no Amount changed, the Set is empty, so the handler returns before running any SOQL or DML.
Exercise
Why can comparing a Name field with != miss a change from 'acme' to 'ACME', and what do you use instead if capitalization matters?
Show answer
In Apex, == and != on Strings are case-insensitive, so 'acme' and 'ACME' are treated as equal and no change is detected. Use String.equals, which is case-sensitive, after checking that the left-hand value is not null.