What’s the Difference Between Before and After Triggers

Sharing is Caring

Apex Triggers don’t need to be complicated. If you have worked with databases like SQL Server or MySQL the triggers execute in a very similar fashion.

Before triggers execute before the data has been committed into the database. This means that if you decided to query the data it either wouldn’t exist if it was an insert or if it’s being updated it would still be the previous values.

One of the most important things to note is that Before triggers don’t have access to the Id fields (on insert), formulas and roll up summaries. I have personally been tripped up by this on many occasions.

The key advantage to the before trigger is that you can modify the values before they have been committed to the database. In other words, this means that the values of Trigger.New can be modified without needing to do additional DML.

After triggers execute after the data has been inserted or updated in the database. Usually, after triggers are used because you need access to a formula field or the Id in the case of an insert.

There are circumstances where it makes sense to use the after trigger though, these circumstances are usually:

  • Updating or Creating records that are not the record being updated or inserted. A really good example of this is adding Opportunity Line Items or a Quote for an Opportunity that has reached a certain Stage.
  • if you need to use the name, auto number, Id, or something in an email or another object it should be done in an after trigger.

In general, most trigger logic will probably be done in the before trigger because you will probably be updating the same object and wouldn’t necessarily want to rerun all of the triggers.

I wouldn’t be surprised if 90% or more of the trigger logic I’ve written has been called from a Before Trigger. The after trigger should really be done to reupdate data or to do something once the data has been committed to the system.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.