Compare Old And New Values In Salesforce Trigger

Salesforce provides trigger.oldmap where in all the old records are stored in map with keyset as their ids. We can compare old field value of records with the new values in trigger.

Here in the below example, the trigger compares the account number old value with the new value. If the account number is changed the trigger assigns the type field value “Customer – Direct” else it assigns it a value “Customer – Channel”.

trigger AccountTrigger on Account (before update) {
    
    for (Account acc: Trigger.new) {
        Account oldAccount = Trigger.oldMap.get(acc.Id);
        if(acc.AccountNumber != oldAccount.AccountNumber) {
            System.debug('--Account Number is changed--');
            System.debug('--Old Account Number -' + oldAccount.AccountNumber);
            System.debug('--New Account Number -' + acc.AccountNumber);
            acc.Type = 'Customer - Direct';
        }
        else{
            System.debug('--Account Number has not been updated--');
            acc.Type = 'Customer - Channel';  
        }
    }
}