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, autonumber, 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 necessary 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.