Compare old and new values in trigger salesforce

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

Here, the trigger compares the account number 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 "prospect" else it assigns it a value "Other" 

trigger Compare_OldandNewvalues on Account (before update) {

   for (Account acc: {
        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 = 'Prospect';
            System.debug('--**Account Number has not been Updated**--');
            acc.Type = 'Other';  

Also, note that the trigger.oldmap values can be accessed only in update and delete triggers and cannot be accessed in insert triggers.


  1. Thank you so much for this piece of code. It really helped me ALOT.

  2. one question on this. When i change an attribute, i don't have to make a DML call, becuase it will be picked up by the update who caused the trigger? Thanks!