SalesforceWizard

Apex trigger interview questions and scenarios

Expect at least one "write a trigger that…" question in a developer interview. Here are the concepts and the code patterns you will need.

0 of 24 reviewed
On this page (5 sections)Trigger basicsWriting trigger logicRecursion, bulk records and data loadsCallouts and testingWhere to go next

Triggers are where most interview coding exercises happen. Expect at least one "write a trigger that…" question. The answers below cover the concepts and include short code you can adapt on a whiteboard.

Questions in each topic go from beginner to advanced. Use On this page to jump to the topic you need.

Trigger basics

01

What is the difference between before and after triggers?

Beginner

What the interviewer is checking: Whether you know before triggers change the same record without DML, and after triggers are for related records and anything needing the Id.

Before triggers run before the record is saved. Use them to set or validate fields on the same record, because changes to Trigger.new are saved without extra DML.

After triggers run once the record has an Id. Use them to create or update related records, or anything that needs the saved record's Id.

Common mistake: Updating the same record with DML in an after trigger, which causes recursion.

02

What are trigger context variables?

Beginner

What the interviewer is checking: Which variables exist in which events, for example Trigger.oldMap is null on insert.

  • Trigger.new / Trigger.newMap: the new versions of the records.
  • Trigger.old / Trigger.oldMap: the previous versions (update and delete only).
  • Trigger.isBefore, isAfter, isInsert, isUpdate, isDelete, isUndelete: where you are.
  • Trigger.operationType: the same information as a single enum, handy in a switch statement.
  • Trigger.size: how many records are in this batch.

Common mistake: Using Trigger.old in an insert trigger.

03

What is the maximum number of records in a trigger batch?

Beginner

What the interviewer is checking: That triggers run in chunks of 200, so code must be bulk-safe for any total.

Triggers process records in chunks of 200. If 1,000 records are inserted in one DML call, the trigger runs five times within the same transaction, and governor limits are shared across all five runs.

Common mistake: Assuming the trigger sees all records of a large data load at once.

04

What is the difference between addError on a record and on a field?

Beginner

record.addError('message') shows the error at the top of the page and stops the save. record.Field__c.addError('message') shows it next to that field, which is clearer for users. Both roll back the record's save.

05

What happens if a trigger throws an unhandled exception?

Beginner

The whole transaction rolls back, including changes made by other triggers and flows in the same transaction. In a bulk DML with allOrNone set to false, only the failing records are rolled back and the rest save.

06

Why should you have only one trigger per object?

Intermediate

Salesforce does not guarantee the order in which multiple triggers on the same object run. With one trigger per object, you control the order inside a handler class, it is easier to debug, and you can add a single bypass switch.

07

When would you use a Flow instead of a trigger?

Intermediate

If the automation is a simple field update or record creation that an admin should maintain, a record-triggered flow is usually the better choice. Choose a trigger for complex logic, large volumes or cases that need precise control over order and error handling.

Writing trigger logic

08

Create a follow-up task when a case is escalated.

Beginner

After insert and after update on Case: when IsEscalated changes from false to true, create a Task linked to the case (WhatId) and assign it to the case owner if the owner is a user, not a queue.

Checking that the owner is a user (the ID starts with 005) is a detail that shows real experience, because tasks cannot be assigned to queues.

09

Write a trigger that stops an Account being deleted if it has open Opportunities.

Intermediate

Use a before delete trigger, query once for all the accounts in the batch, then add an error to the ones that should not be deleted:

trigger AccountTrigger on Account (before delete) {
    Set<Id> blocked = new Set<Id>();
    for (Opportunity o : [SELECT AccountId FROM Opportunity
                          WHERE AccountId IN :Trigger.oldMap.keySet()
                          AND IsClosed = false]) {
        blocked.add(o.AccountId);
    }
    for (Account a : Trigger.old) {
        if (blocked.contains(a.Id)) {
            a.addError('This account has open opportunities and cannot be deleted.');
        }
    }
}

Point out that there is one query for the whole batch, so it works for 1 record or 200.

10

Write a trigger that keeps a count of Contacts on each Account.

Intermediate

This is a classic roll-up for a lookup relationship. Collect the affected Account Ids from insert, update (if AccountId changed), delete and undelete, then recount with one aggregate query:

trigger ContactTrigger on Contact (after insert, after update, after delete, after undelete) {
    Set<Id> accIds = new Set<Id>();
    for (Contact c : Trigger.isDelete ? Trigger.old : Trigger.new) {
        if (c.AccountId != null) accIds.add(c.AccountId);
    }
    if (Trigger.isUpdate) {
        for (Contact c : Trigger.old) if (c.AccountId != null) accIds.add(c.AccountId);
    }
    Map<Id, Account> updates = new Map<Id, Account>();
    for (Id i : accIds) updates.put(i, new Account(Id = i, Contact_Count__c = 0));
    for (AggregateResult ar : [SELECT AccountId a, COUNT(Id) n FROM Contact
                               WHERE AccountId IN :accIds GROUP BY AccountId]) {
        updates.get((Id) ar.get('a')).Contact_Count__c = (Integer) ar.get('n');
    }
    update updates.values();
}

In a real project this logic would live in a handler class, but this shape is what interviewers look for.

11

When an opportunity is closed won, update a field on the account. Write the trigger logic.

Intermediate

Use an after update trigger, collect account IDs only for opportunities that just changed to Closed Won, and update all accounts in one DML.

public static void afterUpdate(List<Opportunity> newList, Map<Id, Opportunity> oldMap) {
    Map<Id, Account> toUpdate = new Map<Id, Account>();
    for (Opportunity o : newList) {
        if (o.IsWon && !oldMap.get(o.Id).IsWon && o.AccountId != null) {
            toUpdate.put(o.AccountId, new Account(Id = o.AccountId, Last_Won_Date__c = o.CloseDate));
        }
    }
    if (!toUpdate.isEmpty()) update toUpdate.values();
}

Checking the old value is what interviewers look for: it stops the update running every time the opportunity is edited.

12

Prevent users from deleting an account that has open cases.

Intermediate

Use a before delete trigger, query accounts that have open cases in one query, and call addError on those records.

public static void beforeDelete(Map<Id, Account> oldMap) {
    for (Account a : [SELECT Id FROM Account WHERE Id IN :oldMap.keySet()
                      AND Id IN (SELECT AccountId FROM Case WHERE IsClosed = false)]) {
        oldMap.get(a.Id).addError('This account has open cases and cannot be deleted.');
    }
}

Note that in a delete trigger you use Trigger.old or Trigger.oldMap; Trigger.new is not available.

13

Keep a count of contacts on each account (roll-up on a lookup).

Intermediate

Handle insert, update (when AccountId changes), delete and undelete. Collect all affected account IDs, including the old account when a contact moves, then recalculate with one aggregate query.

Map<Id, Integer> counts = new Map<Id, Integer>();
for (Id accId : accountIds) counts.put(accId, 0);
for (AggregateResult ar : [SELECT AccountId accId, COUNT(Id) total FROM Contact
                           WHERE AccountId IN :accountIds GROUP BY AccountId]) {
    counts.put((Id) ar.get('accId'), (Integer) ar.get('total'));
}
List<Account> accs = new List<Account>();
for (Id accId : counts.keySet()) accs.add(new Account(Id = accId, Contact_Count__c = counts.get(accId)));
update accs;

Recalculating instead of adding or subtracting 1 keeps the number correct even if an earlier update failed. Today you could also mention that a Flow or a third-party roll-up tool can do this without code.

14

Stop duplicate contacts with the same email being inserted.

Intermediate

Collect the emails from the new records, query existing contacts with those emails, and add an error to any record that matches. Also check for duplicates within the same batch.

In an interview, mention that Salesforce Duplicate Rules and Matching Rules solve this without code. A trigger is only needed for rules that duplicate management can't express.

15

When an account's address changes, update the mailing address on all its contacts.

Intermediate

After update on Account: find accounts whose billing address fields changed, query their contacts in one query, set the mailing fields and update them in one DML.

Mention volume: if an account can have thousands of contacts, move the update to a Queueable or Batch job to stay within limits.

16

When a field changes on a parent record, how do you update all its child records?

Intermediate

What the interviewer is checking: Bulkification and the changed-value check, which together keep the trigger inside limits and stop pointless updates.

Use an after update trigger on the parent (the children need the parent's committed values, and you are changing other records). In the handler:

  • Collect the Ids of parents where the field really changed, comparing Trigger.oldMap with Trigger.new.
  • Query the children once with WHERE ParentId IN :changedIds.
  • Set the new value on each child and update them in one DML statement.
Set<Id> changed = new Set<Id>();
for (Account a : (List<Account>) Trigger.new) {
  if (a.Region__c != ((Account) Trigger.oldMap.get(a.Id)).Region__c) changed.add(a.Id);
}
if (changed.isEmpty()) return;
List<Contact> cons = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :changed];
for (Contact c : cons) c.Region__c = ((Account) Trigger.newMap.get(c.AccountId)).Region__c;
update cons;

If a parent can have thousands of children, move the update to a Queueable or Batch job. A record-triggered flow can do the same for small volumes without code.

Common mistake: Querying children inside the loop, or updating every child on every save even when the field did not change.

Recursion, bulk records and data loads

17

How do you prevent a trigger from running recursively?

Intermediate

Recursion happens when a trigger updates records that fire the same trigger again. Avoid it first by design: do field updates in before triggers so no extra DML is needed.

When you do need a guard, track the record Ids already processed in a static Set rather than a single static Boolean. A Boolean blocks legitimate second batches when more than 200 records are saved in one transaction.

18

How do you bypass triggers during a data load?

Intermediate

Build a bypass into your handler, controlled by a custom permission or a hierarchy custom setting or custom metadata record. The handler checks the flag at the start and exits. That way a data migration user can load records without firing automation, and nobody has to deactivate triggers in production.

19

A trigger works for one record but fails during a data load of 10,000 records. Why?

Intermediate

Almost always SOQL or DML inside a loop, which hits the limit of 100 queries or 150 DML statements per transaction. Data loads send records in batches of up to 200, so a loop with a query fails at the 101st record.

Fix it by bulkifying: collect IDs, query once into a map, change records in memory and do one DML. Then add a test that inserts 200 records.

20

How do you make a trigger skip logic during a data migration?

Intermediate

Use a bypass setting, such as a Custom Permission or a hierarchy Custom Setting, checked at the start of the handler. The migration user gets the bypass; normal users don't.

This is better than deactivating triggers in production, which needs a deployment and affects every user at the same time.

21

Two triggers on the same object conflict. How do you fix it?

Intermediate

Salesforce does not guarantee the order in which multiple triggers on the same object run. Merge them into one trigger per object that calls a handler class, and control the order of logic inside the handler.

I also check Flows on the same object, because record-triggered Flows run in the same transaction and can update the same fields.

Callouts and testing

22

Can you make a callout from a trigger?

Intermediate

Not directly, because a callout cannot happen while the database transaction is open. Call a @future(callout=true) method or enqueue a Queueable that implements Database.AllowsCallouts. Remember that this runs after the transaction commits, so design for failures and retries.

23

Your trigger calls an external API. Why does it fail and how do you fix it?

Intermediate

Callouts are not allowed directly in a trigger, because the transaction would wait on the external system while holding database locks. You get a "callout from triggers are currently not supported" error.

Move the callout to a Queueable class with Database.AllowsCallouts (or an @future(callout=true) method), and pass record IDs, not whole records. For many records, send them in batches.

24

How do you test a trigger properly?

Intermediate

Create test data in the test itself (or in @testSetup), run the DML between Test.startTest() and Test.stopTest(), then query the results and assert on them.

Always include a bulk test with 200 records, a negative test that expects the error, and a test that runs as a user with limited permissions if sharing matters.

Where to go next

Once you are comfortable writing triggers, learn how teams organise them in a trigger framework, and practise the limits that trip triggers up in the governor limits scenarios.

Chat on WhatsApp