Wednesday, 23 May 2018

   DML Statement in 'after trigger' and not in 'before trigger'?


According to document, first Before trigger fire and then after trigger fire.In between of these events all the records saved to database but doesn't committed yet
  • Before insert event
  • Data committed to database
  • After insert event

Means when you use before insert operation records are not committed to database so If we change the trigger context record's value then we don't need perform DML (This is Id is not generated because it is not committed to database)

  • Once it is committed to database means the record Id is generated and your trigger records in read only mode you can't update the values now(because it is committed to database).That's why we need to perform extra DML for updating records.


Note: If in after event if any error occurs then complete DML operation rollback.

Best way if you want to update the same record in trigger then always go with before event. This way you can skip the extra DML.