Intermediate 25 min read

Before and After Triggers

By the end of this lesson, you'll be able to:

  • Distinguish a before trigger from an after trigger
  • Choose the correct trigger timing for a given task
  • Explain why modifying a field only works correctly in a before trigger

Prerequisites: "What Is a Trigger?"

before: modify the record on its way in

trigger AccountTrigger on Account (before insert) {
    for (Account acc : Trigger.new) {
        if (String.isBlank(acc.Industry)) {
            acc.Industry = 'Unknown';
        }
    }
}

A before insert trigger runs before the record is actually saved — this is exactly Module 19's "What Really Happens When You Insert a Record" sequence, step 2. Changing a field here (like defaulting a blank Industry) becomes part of what actually gets saved, with no extra update DML needed.

after: react once the record is permanent

trigger AccountTrigger on Account (after insert) {
    for (Account acc : Trigger.new) {
        System.debug('Account saved with Id: ' + acc.Id);
    }
}

An after insert trigger runs after the save — step 5 from Module 19's sequence — so acc.Id is already populated here. This is the right place for logic that needs the final saved state, like creating a related record that needs this Account's real Id.

Why field changes belong in before, not after

// WRONG PLACE for a field default
trigger AccountTrigger on Account (after insert) {
    for (Account acc : Trigger.new) {
        acc.Industry = 'Unknown'; // too late — already saved without this!
        update acc; // requires an extra, avoidable DML statement
    }
}

By the time an after trigger runs, the record is already saved — changing a field here doesn't retroactively change what was saved; it requires an entirely separate update DML statement to apply the change. This is exactly why Industry defaulting belongs in before insert: the change becomes part of the original save, with no second DML operation needed at all.

Exercise

As a comment, decide whether defaulting a blank Rating field to 'Cold' belongs in a before or after trigger, and explain why.

Show hint

Think about whether an extra DML statement would be needed.

APEX

Before and After Triggers Quiz

1. Why is a before trigger the right place to default a blank field, rather than after?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

before triggers run prior to the actual save and can still modify the record being saved; after triggers run once the save is complete and can see the final, permanent state — including the Id.