Most apex trigger interview questions cover the same six areas: trigger events and the order they fire in, before versus after triggers, which context variables you can use in each event, bulkification, recursion control, and the trigger handler pattern. Mid-level candidates also get asked how they would stop a save with addError, how to make a callout from a trigger, and how they would test the trigger. Below is a model answer and a short code snippet for each, plus a simple way to structure your answers in the room.
How to structure a trigger answer in an interview
Interviewers are checking how you reason, so recall alone won't carry you. A four-part answer works for nearly every trigger question:
- Define it in one sentence. "A before trigger runs before the record is saved to the database."
- Say when you would use it. "I use it to set or validate fields on the same record, because I don't need extra DML."
- Show it or name the edge case. Write a few lines, or point out the trap (for example,
Trigger.newMapis null in before insert). - Say what you would test. "I'd insert 200+ records in a test, assert on the field values, and run it as a user without admin rights."
The fourth step is what separates mid-level candidates from juniors. Ending every answer with "and here's how I'd prove it works" tells the interviewer you have shipped triggers to production.
Q1. What trigger events exist, and where do triggers sit in the order of execution?
Model answer: Apex triggers support seven events: before insert, before update, before delete, after insert, after update, after delete, and after undelete. There is no before undelete.
When a record is saved, Salesforce runs a fixed sequence. A simplified version that covers what interviewers usually look for:
- Load the original record (or initialise a new one) and apply the new field values
- Run system validation (required fields, field formats)
- Run before-save record-triggered flows
- Run before triggers
- Run system validation again, plus custom validation rules
- Run duplicate rules
- Save the record to the database (not committed yet)
- Run after triggers
- Run assignment rules, auto-response rules, and workflow rules (in older orgs, a workflow field update fires before and after update triggers one more time)
- Run after-save record-triggered flows, then roll-up summary and sharing recalculation
- Commit, then post-commit work such as sending emails and running async jobs
Edge case to mention: If one object has several triggers for the same event, Salesforce does not guarantee the order they run in. That is the main argument for one trigger per object (see Q6). Salesforce keeps the full list in its "Triggers and Order of Execution" developer doc, and saying you'd check the doc for the exact steps is a fine answer.
Q2. When do you use a before trigger and when do you use an after trigger?
Model answer: Use a before trigger to validate or change fields on the records being saved. You edit Trigger.new directly and Salesforce saves the changes without an extra DML statement. Use an after trigger when you need values the database sets on save (the record Id, CreatedDate, LastModifiedDate) or when you are creating or updating other records.
trigger OpportunityTrigger on Opportunity (before insert, after insert) {
if (Trigger.isBefore) {
for (Opportunity o : Trigger.new) {
if (o.Probability == null) {
o.Probability = 10; // same-record change, no DML needed
}
}
}
if (Trigger.isAfter) {
List<Task> tasks = new List<Task>();
for (Opportunity o : Trigger.new) {
tasks.add(new Task(WhatId = o.Id, Subject = 'Intro call')); // needs o.Id
}
insert tasks;
}
}
| Need | Before trigger | After trigger |
|---|---|---|
| Set or default a field on the same record | Yes, edit Trigger.new | No, records are read-only |
| Validate and block the save | Yes, with addError | Works, but the save already ran |
Use the record Id on insert | Not available | Available |
| Create or update related records | Avoid | Yes |
Read system fields like CreatedDate | Not populated on insert | Populated |
What to test: For the before trigger, assert the default after insert. For the after trigger, query the related Tasks and assert one exists per Opportunity.
Q3. Which context variables are available in each event?
This question often comes as a trap: "Can you use Trigger.newMap in before insert?" The answer is no, because records have no Ids yet.
| Variable | Insert | Update | Delete | Undelete |
|---|---|---|---|---|
Trigger.new | Yes (editable only in before) | Yes (editable only in before) | No | Yes |
Trigger.newMap | After only | Yes | No | Yes |
Trigger.old | No | Yes | Yes | No |
Trigger.oldMap | No | Yes | Yes | No |
Other variables worth naming: Trigger.isBefore, Trigger.isAfter, Trigger.isInsert, Trigger.isUpdate, Trigger.size, and Trigger.operationType, which returns a System.TriggerOperation value such as BEFORE_INSERT and works well with switch on.
Follow-up you might get: "Why can't you run update Trigger.new in an after trigger?" Because those records are read-only in after context, and calling DML on the same records would fire the trigger again. If you need to change the same record after save, either move the logic to a before trigger or query fresh copies and update those with a recursion guard.
Q4. How do you bulkify a trigger?
Model answer: A trigger receives records in chunks of up to 200, so code must handle a list, never a single record. No SOQL or DML inside loops: collect Ids into a set, query once, put the results in a map, then loop. The synchronous limits are 100 SOQL queries and 150 DML statements per transaction, so a query inside a loop breaks at the 101st record.
Bad version:
for (Contact c : Trigger.new) {
Account a = [SELECT BillingCountry FROM Account WHERE Id = :c.AccountId];
c.MailingCountry = a.BillingCountry;
}
Bulkified version:
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) accountIds.add(c.AccountId);
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, BillingCountry FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account a = accounts.get(c.AccountId);
if (a != null && c.MailingCountry == null) {
c.MailingCountry = a.BillingCountry;
}
}
What to test: Insert 201 Contacts in one statement so the trigger runs across two chunks, then assert every Contact got the country. If you want a longer walkthrough of the "Too many SOQL queries: 101" error, the Salesforce Casts post on Apex bulkification covers it step by step.
Q5. How do you prevent trigger recursion?
Model answer: Recursion happens when a trigger performs DML that fires the same trigger again, directly or through a flow or another trigger. The best guard is to only act when the field you care about actually changed, by comparing Trigger.new with Trigger.oldMap. On top of that, track processed record Ids in a static Set<Id>, which lasts for the whole transaction.
public class TriggerGuard {
private static Set<Id> processed = new Set<Id>();
public static List<SObject> firstTimeOnly(List<SObject> records) {
List<SObject> result = new List<SObject>();
for (SObject rec : records) {
if (!processed.contains(rec.Id)) {
processed.add(rec.Id);
result.add(rec);
}
}
return result;
}
}
The trap interviewers look for: a static Boolean such as hasRun = true. If Apex inserts 1,000 records in one statement, the trigger fires five times (once per 200-record chunk) in the same transaction. The Boolean is set during the first chunk, so the other 800 records are silently skipped. Pointing out this bug is one of the quickest ways to show real experience.
What to test: Update 400 records in a single DML statement and assert all 400 were processed, not just the first 200.
Q6. What is a trigger handler pattern, and why one trigger per object?
Model answer: Keep the trigger itself logic-free. It hands control to a handler class that routes each event to a method. That gives you one trigger per object (so execution order is predictable), logic you can unit test and reuse, and one place to add bypass switches or recursion guards.
trigger AccountTrigger on Account (
before insert, before update, after insert, after update
) {
AccountTriggerHandler.run();
}
public with sharing class AccountTriggerHandler {
public static void run() {
switch on Trigger.operationType {
when BEFORE_INSERT {
setDefaults((List<Account>) Trigger.new);
}
when AFTER_UPDATE {
syncContacts(
(Map<Id, Account>) Trigger.newMap,
(Map<Id, Account>) Trigger.oldMap
);
}
}
}
private static void setDefaults(List<Account> accounts) {
for (Account a : accounts) {
if (a.Rating == null) a.Rating = 'Warm';
}
}
private static void syncContacts(Map<Id, Account> newMap, Map<Id, Account> oldMap) {
// act only on accounts whose BillingCountry changed
}
}
Expect a follow-up on frameworks. You can mention that teams use a virtual base handler class or a metadata-driven framework that lets admins switch a handler off without a deployment. Then say which one you've used and why. The free Apex Triggers Framework 101 course (8 episodes, about half an hour) builds a framework like this from scratch in a real org.
Q7. How do you stop a record from saving?
Model answer: Call addError on the record or field in a before trigger. That record's save is blocked, the user sees the message, and with partial-success DML the other records in the batch can still save.
for (Opportunity o : Trigger.new) {
if (o.StageName == 'Closed Won' && o.Amount == null) {
o.Amount.addError('Amount is required to close a deal.');
}
}
Mention that a validation rule is often the better choice for a simple rule like this. Use a trigger when the check needs a query or logic a formula can't express.
Q8. Can you make a callout from a trigger?
Model answer: Not synchronously. A trigger runs inside the database transaction, and Salesforce blocks callouts there. Enqueue a Queueable that implements Database.AllowsCallouts, or call an @future(callout=true) method, and pass record Ids rather than sObjects.
// in the after insert handler
System.enqueueJob(new SyncToErpJob(new List<Id>(Trigger.newMap.keySet())));
What to test: Use Test.setMock with an HttpCalloutMock, wrap the DML in Test.startTest() and Test.stopTest() so the async job runs, then assert on the result.
Q9. How do you test a trigger?
Model answer: Testing a trigger means proving its behaviour, and 75% coverage on its own proves nothing. A good trigger test suite:
- Inserts or updates 200+ records in one statement to prove bulk safety
- Covers both the positive path and the negative path (the
addErrorcase) - Uses
System.runAsto check behaviour for a non-admin user - Wraps the action in
Test.startTest()/Test.stopTest()to reset limits and run async work - Asserts outcomes with the
Assertclass, with clear messages
@IsTest
private class ContactTriggerTest {
@IsTest
static void copiesCountryInBulk() {
Account acc = new Account(Name = 'Acme', BillingCountry = 'India');
insert acc;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 201; i++) {
contacts.add(new Contact(LastName = 'Test ' + i, AccountId = acc.Id));
}
Test.startTest();
insert contacts;
Test.stopTest();
for (Contact c : [SELECT MailingCountry FROM Contact WHERE AccountId = :acc.Id]) {
Assert.areEqual('India', c.MailingCountry, 'Country should copy from Account');
}
}
}
The post on Apex test classes beyond 75% coverage goes further into what to assert.
Q10. When would you choose a trigger over a record-triggered flow?
Model answer: For simple same-record field updates, a before-save flow is quick to build and admins can maintain it. I pick a trigger when the logic involves complex branching, large data volumes, reusable Apex services, callouts orchestrated through async Apex, or anything that needs proper unit tests. On an object that already has a trigger framework, I keep related logic in one place so the order of execution stays predictable.
Interviewers rarely want a single "right" answer here. They want to see that you've thought about who maintains the automation and how it behaves at volume.
How Salesforce Casts fits into interview prep
Every Salesforce Casts course is taught by Teja, an ex-engineer at Salesforce.com, and built live in a real org line by line, with no slide decks. For trigger interviews, the most relevant pieces are:
- Apex Triggers Framework 101: free, 8 episodes, about 0.5 hours. A good place to start if the handler pattern is new to you.
- Apex Test Fest: covers async tests,
System.runAs, theAssertclass and callout mocks, which is the material behind "what would you test" answers. - Interview Questions course: included in every plan, because every plan unlocks every course.
- Salesforce Interview Questions & Answers Book: 700+ pages, available only with the Lifetime plan ($249 one-time, or โน12,999 in India).
Every course comes with a GitHub repo, so you can run the trigger code yourself before you have to explain it. Two limits to know before you buy: Salesforce Casts doesn't drill certification exam questions (use Trailhead for that) and makes no placement promises. There are no live classes or 1:1 mentoring either. Questions go to the private discussion group.
FAQ
Will I have to write a trigger live in the interview?
Often, yes, either in a shared editor or on a whiteboard. Practise writing a bulkified trigger and handler from memory, including the Set-then-Map pattern from Q4. Talk through your choices as you type, and finish by saying what test you would write.
Do I need to memorise the full order of execution?
You need the main sequence: before-save flows, before triggers, validation rules, save, after triggers, after-save flows, commit. Interviewers mostly check that you know where triggers sit relative to validation rules and flows. Saying you would confirm the exact steps in Salesforce's documentation is an acceptable answer.
Is the Interview Questions & Answers Book included in the Monthly or Yearly plan?
No. The 700+ page book is a Lifetime plan exclusive. The Monthly ($19/month, โน1,999 in India) and Yearly ($149/year, โน7,499 in India) plans include the Interview Questions course and every other course in the catalogue. Plan details are on the pricing page.
Should I learn triggers or Flow first?
If you're aiming for a developer role, learn both, but expect harder questions on triggers because they test your Apex. Admin-leaning roles weight Flow more heavily. Either way, you should be able to explain when you'd choose one over the other (Q10).
Can I try the content before paying?
Yes. Three courses are free: Apex Triggers Framework 101, JavaScript for Lightning Web Components, and Salesforce Administration Training. Salesforce Casts has a no-refunds policy, so watching a free course first is the sensible way to check whether the teaching style suits you.
How should I prepare in the last week before an interview?
Write one trigger per day from scratch with a handler, a recursion guard and a 200-record test. Then say your answers out loud using the define, use, show, test structure. The 30-day developer interview plan breaks down a longer schedule if you have more time.
Next step
Start with the free Apex Triggers Framework 101 course tonight, and rebuild its handler in your own Developer Edition org before your next interview. When you want the full question bank, compare plans on the Salesforce Casts pricing page.
Learn it by building it
Every course, every code repository, the discussion group and certificates of completion โ one subscription.
Keep going
Blog
Apex Test Data Factory: A Reusable Pattern for Test Classes
Blog
Governor Limits in Salesforce: What They Are and How to Stay Under Them
Blog
Named Credentials in Salesforce: Setup and Use in Apex
Blog
How to debug failures in Platform Events?
Blog
Retrying Failed Callouts in Salesforce Apex: Best Practices with Code Snippet
Blog
How to create REST API in Apex