Skip to main content
New tool CRON Expression Builder — preview next run times before you schedule Apex. Open the builder →
A developer writing complex Apex code focusing on Apex Trigger Interview Questions for a technical role.
Apex

Apex Trigger Interview Questions and Real Code Scenarios

Prepping for a Salesforce technical interview? These Apex Trigger Interview Questions run from before vs after logic through to recursion, with the real code an interviewer will ask you to write on the whiteboard.

The short answer

This article covers the Apex trigger questions interviewers actually ask, along with the design patterns and coding scenarios behind them: choosing trigger events, bulkifying code, avoiding recursion, handling mixed DML, and blocking record operations with custom logic.

Key takeaways Use a before trigger to modify fields on the same record and skip an extra DML step. Use an after trigger when you need record IDs or have to modify related records. Bulkify every trigger by keeping SOQL queries and DML statements outside loops, with Sets and Maps to handle 200-record chunks. Stop infinite trigger recursion by tracking execution state in a static boolean variable on a helper class. Keep one trigger per object and route the business logic to handler classes so the trigger itself stays thin. Call addError() on Trigger.old in a before delete trigger to block deletions that break a business rule.

Mastering the most common Apex Trigger Interview Questions

If you are prepping for a technical round, you know that Apex Trigger Interview Questions are basically guaranteed to come up. I've sat on both sides of the table, and honestly, interviewers don't care if you can recite a textbook definition. They want to know if you are going to break their production org with a non-bulkified loop or a recursive nightmare. What they are checking is how you handle the logic that Flow can't cover.

The "when to use a trigger" conversation has changed. With the recent updates to Flow, we are using code less often for simple updates. But for complex cross-object logic or high-volume processing, triggers are still the gold standard. When you are answering Apex Trigger Interview Questions, you need to show where that code sits in the rest of the org.

1. Before vs After triggers: which one and why?

This is usually the first thing they'll ask. The short answer? Use a "Before" trigger if you are updating fields on the same record that fired the trigger. It is faster because it saves an extra DML step. Use an "After" trigger when you need the record Id (which doesn't exist until the record hits the database) or when you need to update related records. Here is a simple look at how we split that logic:

trigger AccountTrigger on Account (before insert, after insert) {
    if(Trigger.isBefore && Trigger.isInsert){
        for(Account acc : Trigger.new){
            // Modifying the record before it saves - no DML needed
            acc.Description = 'New Account Verified';
        }
    }
    if(Trigger.isAfter && Trigger.isInsert){
        // We have the ID now, so we can do stuff with related records
        System.debug('New Account Created with Id: ' + Trigger.new[0].Id);
    }
}

A split-screen view of a code editor with Apex trigger logic next to a Salesforce record detail page.

A split-screen view of a code editor with Apex trigger logic next to a Salesforce record detail page.

Why Apex Trigger Interview Questions focus on real-world scenarios

Interviewers love to trip you up with recursion. A recursive trigger happens when your code performs an update that fires the same trigger again, creating an infinite loop. I've seen this most often when an "After Update" trigger updates the same record. The standard fix is a helper class with a static boolean flag, so the code runs only once per transaction.

public class TriggerHelper {
    public static Boolean hasRun = false;
}

trigger ContactTrigger on Contact (after update) {
    if(!TriggerHelper.hasRun) {
        TriggerHelper.hasRun = true;
        // Your logic here
    }
}

One warning from experience: be careful with static flags if you are dealing with large data sets where the trigger might fire in multiple chunks of 200 records. Sometimes you need a more specific way to track which records have been processed so you don't skip valid logic.

2. The golden rule: bulkification

If you put a SOQL query or a DML statement inside a for loop during a live coding challenge, the interview is probably over. You have to write code that handles 200 records at once. Use Sets to collect IDs and Maps to link related data. That is what keeps you managing large data volumes without hitting governor limits.

Set<Id> accIds = new Set<Id>();
for(Contact con : Trigger.new){
    accIds.add(con.AccountId);
}
// Query once, outside the loop
Map<Id, Account> parentAccounts = new Map<Id, Account>([SELECT Id, Name FROM Account WHERE Id IN :accIds]);

for(Contact con : Trigger.new){
    Account parent = parentAccounts.get(con.AccountId);
    // Do your logic
}

3. Handling async calls and mixed DML

Sometimes a trigger needs to do something heavy, like calling an external API or processing a massive calculation. You can't make a web service callout directly from a trigger; you have to use @future or Queueable Apex. This also helps you avoid the "Mixed DML" error, which happens when you try to update a User record (Setup object) and an Account (Non-Setup object) in the same transaction. If you're worried about limits, check out this guide on staying under async limits.

Practical tip: always check whether you are already in an asynchronous context before calling a @future method from a trigger, or you might hit a limit exception that is hard to debug.

4. The order of execution

You don't need to memorize all 20 steps, but you should know the big ones. When you save a record, Salesforce runs system validation, "Before" triggers, custom validation rules, "After" triggers, and then Flows. Knowing that validation rules run after "Before" triggers is a common trick question.

5. Trigger design best practices

When I'm reviewing code for a project, I look for these three things immediately:

  • One trigger per object. Don't create five different triggers on the Account object. It makes the order of execution impossible to predict.
  • Logic-less triggers. Your trigger should just be a router. Move the actual "meat" of the code into a Handler class.
  • Bulkification. No queries in loops. Ever.

If you want to see how these concepts fit into a broader interview, I've put together a list of scenario-based questions that go deeper into these patterns. Knowing the syntax is one thing. Knowing when to use code over Flow on a real project is another.

Example: preventing deletion with logic

Here is a classic scenario: "Prevent an Account from being deleted if it has related Contacts." You'll use addError() on Trigger.old to stop the transaction. Notice the Aggregate query, which keeps the whole thing bulkified.

trigger AccountDeleteGuard on Account (before delete) {
    Set<Id> accIds = new Set<Id>();
    for(Account acc : Trigger.old) accIds.add(acc.Id);

    Map<Id, AggregateResult> results = new Map<Id, AggregateResult>([
        SELECT AccountId Id, COUNT(Id) cnt FROM Contact 
        WHERE AccountId IN :accIds GROUP BY AccountId
    ]);

    for(Account acc : Trigger.old){
        if(results.containsKey(acc.Id)){
            acc.addError('You cannot delete this account because it has active contacts.');
        }
    }
}

Key takeaways for your interview

  • Before triggers are for field updates; After triggers are for related record logic.
  • Always use a Map/Set pattern to keep your code bulkified.
  • Use a static boolean flag in a helper class to prevent recursive loops.
  • Keep your triggers "thin" by moving logic to handler classes.
  • Mention addError() as the way to block DML based on custom business logic.

The person interviewing you wants to know whether they can trust you with their code base. If you talk about bulkification, handler patterns, and governor limits, you are already ahead of 90% of the other candidates. Focus on the "why" behind the code.

Frequently asked questions

When should you use a before trigger vs an after trigger in Salesforce?

Use a before trigger when you are modifying fields on the same record that fired the event. It saves an extra DML step, so it is faster. Use an after trigger when you need the system-generated record ID or have to update related records.

How do you prevent recursion in an Apex trigger?

Keep a static boolean flag in a helper class so the logic runs only once per transaction. With large data sets that arrive as several 200-record chunks, track the individual records you have already processed rather than relying on one boolean flag.

How do you avoid mixed DML errors in Apex triggers?

Mixed DML errors happen when you insert or update setup objects and non-setup objects in the same transaction. In a trigger, move one of the operations into an asynchronous context with @future or Queueable Apex.

How do you prevent record deletion in an Apex trigger?

Write a before delete trigger and call addError() on the affected records in Trigger.old when your conditions are met.

Newsletter

One email every Tuesday

New guides, tool updates, and the release-note changes that break things.

No spam. Unsubscribe in one click.

Comments

Loading comments...

Leave a Comment