What is the exact difference between before update and after update trigger?

  • Even though both are doing almost the same function while triggering , what is the precise difference between these two

  • When you save a record (insert / update) Salesforce fires a DML statement to its database, internally.

    All the code written in the "before update" triggers, executes BEFORE that DML is committed to Salesforce Database. Code written in after trigger executes AFTER the commit is made.

    Hence if you are trying to update any value in the record, on which the trigger is fired, you need not write an update call, specifically. But you need to do it in after triggers.

    example, if a before trigger is written on Account and you want to change a value of one of the fields it would be

    for(Account acc: Trigger.new)
    {
    if(acc.value__c='Temp')
        acc.Value__c = 'New value';
    }
    

    but if you will write this on after update you can't update the same field because data is already committed to database so value will be read only.

    After update trigger generally works when you want to update any other object. for example if you want to create a new task on account insertion or update you can write logic for that.

    Thanks @Himanshu, you explained really well.

    • Before triggers are used to update or validate record values before they’re saved to the database.
    • After triggers are used to access field values that are set by the system (such as a record's Id or LastModifiedDate field), and to effect changes in other records. The records that fire the after trigger are read-only.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used