Sub topic 16
Triggers in the order of execution
This chapter assumes you can write before and after triggers, read Trigger.new and Trigger.oldMap, and know that governor limits apply to a whole transaction. It shows where your trigger code sits among the other things Salesforce does when it saves a record. That position decides what your trigger can see and which other automation can undo or repeat its work.
Why the order matters
A trigger is one step in a longer save process. Validation rules, flows, duplicate rules, workflow rules, and roll-up summary recalculation all run in a fixed sequence around it. Three practical questions depend on that sequence:
- Does my before trigger see values that a flow has already changed?
- Do validation rules run before or after my code?
- If a later step fails, is the work done by my after trigger kept?
The simplified sequence
Salesforce documents a longer list, but the steps below are the ones that affect trigger authors. They are for a single save of one record, such as an insert or an update.
| Step | What happens | Why it matters for triggers |
|---|---|---|
| 1 | The original record is loaded, or a new record is initialized. New field values from the request overwrite the old ones. | `Trigger.old` comes from the loaded record. `Trigger.new` holds the incoming values. |
| 2 | System validation runs for requests from the standard UI, such as required fields, field formats, and maximum length. | Bad formats are rejected before your code runs, but only for UI saves. |
| 3 | Record-triggered flows configured to run before save run. | A before trigger sees the values these flows set. |
| 4 | Before triggers run. | You can change `Trigger.new` directly. No DML is needed. |
| 5 | Most system validation runs again, then custom validation rules run. | Rules see the values your before trigger wrote. |
| 6 | Duplicate rules run. | A duplicate block can stop the save before the after trigger runs. |
| 7 | The record is saved to the database but not committed. | Record Ids now exist for inserts. |
| 8 | After triggers run. | Records are read-only. You can do DML on other records. |
| 9 | Assignment rules, auto-response rules, and workflow rules run. | Legacy automation can modify the record again. |
| 10 | If a workflow field update changed the record, it is updated again. Before update and after update triggers run one more time. | Your trigger can run twice in one transaction for one user action. |
| 11 | Escalation rules run, then processes and flows that run after save. | Flows that update records can fire triggers again. |
| 12 | Roll-up summary fields are recalculated, and the parent record goes through its own save process. | A child save can fire the parent's triggers. |
| 13 | Criteria-based sharing is evaluated. | Sharing recalculation happens before the commit. |
| 14 | All DML is committed to the database. | Only now do the changes become permanent. |
| 15 | Post-commit logic runs, such as sending email and starting queued asynchronous jobs. | Emails and enqueued jobs are not sent or started if the transaction rolls back. |
The main points to take from the table:
- Before triggers run early, ahead of custom validation. They are the right place to fix or default values.
- After triggers run once the record has been saved but not committed. Their work is still rolled back if any later step throws an error.
- Every step shares one transaction and one set of governor limits.
Seeing the order for yourself
A debug log shows the real sequence. This trigger writes a log line in each phase and trims whitespace in the before phase.
trigger OrderDemoTrigger on Account (before insert, after insert) {
if (Trigger.isBefore) {
for (Account a : Trigger.new) {
System.debug('BEFORE insert: Id=' + a.Id + ', Name=[' + a.Name + ']');
if (a.Name != null) {
a.Name = a.Name.trim();
}
}
} else {
for (Account a : Trigger.new) {
System.debug('AFTER insert: Id=' + a.Id + ', Name=[' + a.Name + ']');
}
}
}Run this in Anonymous Apex, then open the debug log and filter on USER_DEBUG:
insert new Account(Name = ' Acme ');The before line shows a null Id and the padded name. The after line shows an Id and the trimmed name. The value was changed in memory by the before trigger and saved without a DML statement, as you saw in the earlier chapter on before triggers.
What this means for your code
Before triggers see flow changes, validation rules see trigger changes
Before-save flows run ahead of before triggers, so Trigger.new already contains the flow's changes. Validation rules run after before triggers, so they judge your trigger's output. If you normalize a phone number in a before trigger, a validation rule that checks the phone format sees the normalized value.
Before triggers can also run when the record would later fail validation. Do not assume the data in a before trigger is valid. Check for nulls and unexpected values.
After triggers can be rolled back
An after trigger that inserts a Task has not committed it. If a roll-up summary recalculation or a later trigger on a related record throws an exception, the Task insert is rolled back along with the original save. This is usually what you want. It also means you should not treat after-trigger work as final.
Triggers can run more than once per save
Three things can make your trigger run again in the same transaction:
- A workflow field update re-runs before update and after update triggers once.
- A flow or another trigger updates the same record.
- Your own after trigger does DML on the same object, as in the recursion chapter.
Salesforce stops a chain of triggers that fire other triggers at a stack depth of 16 and throws an exception. Do not rely on that limit to protect you.
The static guard has a trap
The simple Boolean guard from the recursion chapter blocks every later run in the transaction. After a workflow field update, the second run might be the one that has the final values, and the guard would skip it. A guard that records which record Ids you have already processed is more precise.
public class RecordGuard {
private static Set<Id> processedIds = new Set<Id>();
public static List<Account> filterUnprocessed(List<Account> records) {
List<Account> toProcess = new List<Account>();
for (Account a : records) {
if (a.Id == null || !processedIds.contains(a.Id)) {
toProcess.add(a);
if (a.Id != null) {
processedIds.add(a.Id);
}
}
}
return toProcess;
}
}Records with a null Id, which are the ones in a before insert trigger, always pass the filter, because they cannot be tracked yet. Use this filter only in after-phase logic. The set also never clears within a transaction, so a record that legitimately needs a second pass is skipped. If your logic must react to a workflow update, compare values against Trigger.oldMap instead of using a guard.
Several triggers on one object have no guaranteed order
Salesforce does not define the order in which multiple triggers on the same object and event run. Do not write two triggers that depend on each other's output. One trigger per object that calls a handler class, as covered in the handler chapter, keeps the order of your logic under your control.
Flows and triggers interact
A before-save flow is cheap and runs ahead of your trigger. An after-save flow that updates the same record starts a new save and fires your triggers again. When you add a record-triggered flow to an object that already has triggers, review both for repeated work.
Common errors
- Validating in a before trigger and expecting a flow to have run later. Before-save flows run first. Move the check, or accept the flow's value as input.
- Calling
updateonTrigger.newrecords in a before trigger. This is not needed and causes an error. Assign to the fields directly. - Assuming the order of two triggers on one object. Merge them into one trigger.
- Reading a roll-up summary field in a before trigger and expecting a fresh value. Roll-up recalculation happens after the save, so the field holds the previous value.
- Using a
Booleanstatic guard on an object that has workflow field updates. The second legitimate run is skipped. Track Ids or compare old and new values.
Exercise
An Opportunity has a validation rule that requires Amount to be greater than 0 on save. A before update trigger sets Amount to 100 whenever it is null. A before-save flow sets Amount to null when StageName is 'Prospecting'. A user saves an Opportunity in the 'Prospecting' stage. Does the save succeed, and why?
Show answer
The save succeeds. Before-save flows run before before triggers, so the flow sets Amount to null first. The before trigger then sees null and sets it to 100. Validation rules run after before triggers, so the rule sees 100 and passes. If the trigger ran first, the flow would leave Amount null and the validation rule would block the save.
Exercise
Your after update trigger on Account inserts a Task for each changed record. A workflow field update on Account then fires the trigger a second time, and you now get duplicate Tasks. Name two ways to prevent this.
Show answer
Compare each record with Trigger.oldMap and create a Task only when the field you care about actually changed, since the second run often has no meaningful change. Alternatively, track the processed record Ids in a static Set<Id> and skip Ids already handled in this transaction. A plain Boolean guard also stops the duplicates, but it can skip a later run that needs to do real work.