LearnFrenzy
Sign in Take a free test

Salesforce Apex interview · Set 3 of 7

Apex Triggers and Trigger Frameworks

  • 6 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Thin triggers, smart handlers

Choose before vs after correctly, use context variables to detect real changes, know the order of execution, and keep logic in a bulk-safe handler.

  • EventsBefore vs after and context variables.
  • PlatformOrder of execution and validation.
  • DesignHandler pattern and recursion control.

Triggers are where Apex meets real business rules — and where most production bugs live. Interviewers check that you pick before or after correctly, know the context variables, understand the order of execution and keep triggers thin with a handler.

1. Before vs after triggers — when do you use each?

Before triggers change or validate the records being saved — set fields on Trigger.new directly, no DML needed, and it is faster. After triggers act once the records have Ids and are saved — creating related records, updating other objects, calling async processes. Rule of thumb: same record → before; other records → after.

trigger OpportunityTrigger on Opportunity (before insert, before update, after update) {
    if (Trigger.isBefore) {
        for (Opportunity o : Trigger.new) {
            if (o.Amount != null && o.Amount > 1000000) o.Needs_Approval__c = true;   // same record: no DML
        }
    }
}

2. Explain the trigger context variables.

  • Trigger.new / Trigger.old — lists of new and old versions.
  • Trigger.newMap / Trigger.oldMap — maps by Id (newMap not available in before insert).
  • Trigger.isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter — which event fired.
  • Trigger.operationType — a single enum value such as AFTER_UPDATE.
  • Trigger.size — number of records.

Trigger.old is unavailable on insert, and Trigger.new is unavailable on delete.


3. How do you detect that a field actually changed?

Compare the new value with Trigger.oldMap. Acting only on real changes avoids extra work and recursion.

for (Opportunity o : Trigger.new) {
    Opportunity old = Trigger.oldMap.get(o.Id);
    if (o.StageName != old.StageName && o.StageName == 'Closed Won') {
        wonIds.add(o.Id);
    }
}

4. What is the order of execution when a record is saved?

In summary: system validation → before-save record-triggered flows → before triggers → most system and custom validation rules → duplicate rules → record saved (not committed) → after triggers → assignment, auto-response and workflow rules → processes and after-save flows → escalation rules → entitlement rules → roll-up summary and cross-object updates on parents → criteria-based sharing → commit → post-commit logic such as emails and async jobs. Field updates from workflow rules can re-fire before and after update triggers once more.


5. Why use a trigger handler pattern?

Keep one trigger per object with no logic in it; delegate to a handler class with methods per event. Benefits: predictable order, testable methods, easy bypass for data loads, and no conflicting triggers on the same object.

trigger AccountTrigger on Account (before insert, before update, after insert, after update) {
    new AccountTriggerHandler().run();
}

public with sharing class AccountTriggerHandler {
    public void run() {
        switch on Trigger.operationType {
            when BEFORE_INSERT { setDefaults((List<Account>) Trigger.new); }
            when BEFORE_UPDATE { validateRegion((List<Account>) Trigger.new, (Map<Id, Account>) Trigger.oldMap); }
            when AFTER_UPDATE  { syncContacts((Map<Id, Account>) Trigger.newMap, (Map<Id, Account>) Trigger.oldMap); }
        }
    }
    private void setDefaults(List<Account> records) { /* ... */ }
    private void validateRegion(List<Account> records, Map<Id, Account> oldMap) { /* ... */ }
    private void syncContacts(Map<Id, Account> newMap, Map<Id, Account> oldMap) { /* ... */ }
}

6. How do you prevent trigger recursion?

Recursion happens when a trigger updates records that fire the same trigger again. The best fix is to act only on records whose relevant fields changed. A static set of processed Ids is a safe guard; a single static boolean is risky because it blocks later chunks of a bulk load.

public class TriggerGuard {
    private static Set<Id> processed = new Set<Id>();
    public static List<SObject> firstTime(List<SObject> records) {
        List<SObject> fresh = new List<SObject>();
        for (SObject r : records) if (processed.add(r.Id)) fresh.add(r);   // add() returns false if already present
        return fresh;
    }
}

7. How do you show a validation error from a trigger?

Call addError() on the record (or a specific field) in a before trigger. The save is blocked for that record and the message appears to the user, with no DML exception thrown.

for (Case c : Trigger.new) {
    if (c.Priority == 'High' && String.isBlank(c.Description)) {
        c.Description.addError('Please describe the issue for high-priority cases.');
    }
}

8. Trigger or Flow — how do you decide?

Prefer declarative record-triggered flows for straightforward field updates, record creation and notifications that admins can maintain. Use Apex triggers for complex logic, large data volumes, heavy processing, complex error handling, callouts via async Apex, or when you need fine-grained control and unit tests. Avoid mixing both for the same logic on one object.


Remember

Key points

  • Same record → before

    Other records → after.

  • Compare with oldMap

    Act only on real changes.

  • One trigger per object

    Logic in a handler class.

  • Avoid static boolean guards

    Track processed Ids instead.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 Can you do DML on Trigger.new in an after trigger? Intermediate

    No — Trigger.new is read-only in after triggers. Query or clone the records and update them, carefully avoiding recursion.

  2. 2 What happens to Trigger.newMap in a before insert trigger? Basic

    It is null because records have no Ids yet.

  3. 3 How do you write a trigger that rolls up child amounts to a parent? Intermediate

    Collect parent Ids from inserted, updated (old and new parent), deleted and undeleted children, run one aggregate query grouped by parent, and update parents once.

  4. 4 Which triggers fire on a merge? Advanced

    Before and after delete on the losing records and before and after update on the winning record; losing records have MasterRecordId set.

  5. 5 How do you bypass triggers during a data migration? Intermediate

    Check a Custom Permission or hierarchy custom setting in the handler and skip logic for the integration user.

  6. 6 Are triggers fired by a mass update in Data Loader? Basic

    Yes — triggers fire for API operations too, in chunks of up to 200 records.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links