Compare old and new field values in trigger

Compare old and new field values in trigger Salesforce

Sometimes we have requirement that our trigger should run only when some field value is changed on a record. So we need to compare value of that field between old version of record and new version of record to make sure that trigger will not run every time when record is changed/edited. For example, we may have requirement that send an email to VP of company or do some task when an opportunity status is changed to Closed Won. So, we have to compare old and new field values in trigger to make it sure.

It also help to avoid recursive run of trigger. Check this link for how we can avoid recursive trigger in salesforce.

Salesforce provides Trigger.OldMap where records with older version (last version of record committed in database) are stored in map with key as their Salesforce record Id’s.

Trigger.OldMap = Map<Id, OldVersionOfRecord>();

I have put an example below to show that how can we use Trigger.OldMap and Trigger.New context variables to compare the field values, because the Id of the record is common in both Trigger.OldMap and Trigger.New, that’s why we can use the record Id to get older and newer version of any record from these maps.

Here in this example, trigger compares the account number field’s old value with the new value. That is, trigger checks if the account number was changed.

If the account number is changed the trigger assigns the Type field value as “prospect” else it assigns it a value as “Other“.

trigger Compare_OldandNewvalues on Account (before update) {

//Here we will iterate on list, which already holds the new values of all records.
for (Account acc: {
//Here we use the account id, to get the older version of record.
Account oldAccount = Trigger.oldMap.get(acc.ID);

//once we get the older version, we can get any field's value from older version to compare.
if(acc.AccountNumber != oldAccount.AccountNumber) {

//Here is some logic being performed on a condition basis.
System.debug('--*Account Number is changed*--');
System.debug('**Old Account Number :'+oldAccount.AccountNumber);
System.debug('**New Account Number :'+acc.AccountNumber);
acc.Type = 'Prospect';
System.debug('--**Account Number has not been Updated**--');
acc.Type = 'Other';

Also, please note that the Trigger.oldMap is only available in update and delete events and cannot be accessed in insert event triggers. Please take care of this point when writing your trigger code.

Happy coding !! 🙂


Permanent link to this article:

1 comment

    • arun on May 1, 2021 at 11:27 am
    • Reply

    Can I compare old field values and new field values in afterupdate trigger???
    this example is for before update.

Leave a Reply

Your email address will not be published.