Top Salesforce Trigger Interview Questions (With Answers)


Salesforce triggers are an essential part of Apex programming that allow developers to perform custom actions before or after changes to Salesforce records. Whether you're preparing for a job interview or brushing up on your knowledge, this guide will help you master the most commonly asked Salesforce trigger interview questions.
📌 What is a trigger in Salesforce?
A trigger is a piece of Apex code that executes before or after the following types of operations: insert, update, delete, merge, upsert, and undelete. Triggers are used to perform custom logic like validation, automation, or integration when data changes.

🔥 Common Salesforce Trigger Interview Questions
1. What are the types of triggers in Salesforce?
Answer: Salesforce supports two main types of triggers, each serving a distinct purpose in the data processing lifecycle:
- Before Triggers:
- These triggers execute before a record is saved to the database. They are primarily used to validate or modify record values before the actual database operation occurs.
- Use Cases:
- Automatically populating or modifying field values (e.g., setting a default value if a field is blank).
- Validating data and preventing the save operation if certain conditions are not met (using the
addError
method).
- Example:
- If you want to ensure that an Opportunity's
Amount
is always positive before saving, you can use a before trigger to check and throw an error if it's not.
- If you want to ensure that an Opportunity's
- After Triggers:
- These triggers execute after a record has been saved to the database. They are used when you need to access system-generated values (like the record
Id
) or perform operations that require the record to exist in the database. - Use Cases:
- Creating related records (e.g., creating a child record after a parent record is inserted).
- Sending notifications or integrating with external systems.
- Updating related objects based on changes in the current record.
- Example:
- After an Account is created, you might want to automatically create a related Contact record.
- These triggers execute after a record has been saved to the database. They are used when you need to access system-generated values (like the record
Best Practice:
- Use before triggers for validation and field updates on the same object.
- Use after triggers for operations that require the record's Id or involve related objects.
2. Can we call a batch class from a trigger?
Answer: Yes, it is technically possible to call a batch class from a trigger, but it should be done with extreme caution. Batch Apex is designed for processing large volumes of data asynchronously, while triggers are meant for quick, synchronous operations. Directly invoking a batch job from a trigger can lead to performance issues and hitting Salesforce governor limits, especially if the trigger is processing many records at once.
Best Practices:
- Avoid calling batch jobs directly from triggers. Instead, consider using a future method or Queueable Apex to queue the batch job. This approach helps manage execution context and reduces the risk of hitting limits.
- Governor Limits: Salesforce restricts the number of batch jobs and asynchronous calls that can be made in a single transaction. If a trigger fires multiple times (e.g., during a bulk data load), you could easily exceed these limits.
- Example:
- Use a Queueable Apex class to enqueue a batch job, and call the Queueable from the trigger if necessary.
Summary:
- While possible, calling a batch class from a trigger is discouraged. Always consider the impact on system resources and governor limits, and use asynchronous processing patterns where appropriate.
3. What is a recursive trigger? How do you avoid it?
Answer: A recursive trigger occurs when a trigger causes itself (or another trigger on the same object) to execute repeatedly, potentially resulting in an infinite loop and hitting Salesforce governor limits. This can happen, for example, if a trigger performs a DML operation (insert, update, delete) on the same object it is triggered by.
Example of Recursion:
- An update trigger on the Account object updates a field on Account, which causes the trigger to fire again, and so on.
How to Avoid Recursive Triggers:
- Static Variables: Use a static Boolean variable in an Apex class to track whether the trigger has already run in the current context. Static variables retain their value throughout the transaction, preventing repeated execution.
- Example:
public class TriggerHelper {
public static Boolean isFirstRun = true;
}
// In the trigger:
if (TriggerHelper.isFirstRun) {
// logic here
TriggerHelper.isFirstRun = false;
}
- Helper Classes: Encapsulate trigger logic in a handler or helper class, and use flags or static variables to control execution.
- Design Patterns: Use frameworks or trigger patterns (like the Trigger Handler pattern) to centralize logic and manage recursion.
Best Practice:
- Always design triggers to be bulk-safe and recursion-proof. Test with bulk data operations to ensure no infinite loops occur.
4. What are trigger context variables?
Answer: Salesforce provides a set of trigger context variables that give you information about the current execution context of a trigger. These variables help you write logic that adapts to different trigger events and scenarios.
Common Context Variables:
Trigger.isInsert
,Trigger.isUpdate
,Trigger.isDelete
,Trigger.isBefore
,Trigger.isAfter
: Boolean flags indicating the type and timing of the trigger event.Trigger.new
: A list of the new versions of the records being processed (available in insert, update, and undelete triggers).Trigger.old
: A list of the old versions of the records (available in update and delete triggers).Trigger.newMap
: A map of record IDs to the new versions of the records (available in before update, after update, and after insert triggers).Trigger.oldMap
: A map of record IDs to the old versions of the records (available in update and delete triggers).
Usage Examples:
- Use
Trigger.isInsert
to run logic only when records are being inserted. - Use
Trigger.oldMap
andTrigger.newMap
to compare field values before and after an update.
Best Practice:
- Always use context variables to make your trigger logic event-specific and bulk-safe. Avoid hardcoding logic for a single event type.
5. What is the difference between Trigger.new
 and Trigger.old
?
Answer:
Trigger.new
:- Contains a list of the new versions of the records that are being inserted, updated, or undeleted.
- Available in
before insert
,after insert
,before update
,after update
, andafter undelete
triggers. - You can modify the records in
Trigger.new
in before triggers to change field values before they are saved. - Example: In a before update trigger, you can set a field value on each record in
Trigger.new
.
Trigger.old
:- Contains a list of the old versions of the records before they were updated or deleted.
- Available in
before update
,after update
,before delete
, andafter delete
triggers. - Records in
Trigger.old
are read-only. - Example: In an update trigger, you can compare values in
Trigger.old
andTrigger.new
to detect changes and enforce business rules.
Summary Table: | Context | Trigger.new | Trigger.old | |-----------------|-------------|-------------| | Insert | Yes | No | | Update | Yes | Yes | | Delete | No | Yes | | Undelete | Yes | No |
Best Practice:
- Use
Trigger.new
for accessing or modifying new data, andTrigger.old
for comparing previous values or enforcing restrictions on changes.
6. Can you perform DML operations in a before trigger?
Answer: Technically, you can perform DML (Data Manipulation Language) operations—such as insert, update, delete, or undelete—inside a before trigger, but it is strongly discouraged and considered a bad practice. The main reason is that before triggers are designed to allow you to make changes directly to the records in Trigger.new
before they are saved to the database. Performing explicit DML operations in a before trigger can lead to unexpected behavior, recursion, and governor limit issues.
Best Practices:
- ModifyÂ
Trigger.new
 directly: In a before trigger, you should update the fields of the records inTrigger.new
as needed. Salesforce will automatically save these changes when the trigger finishes. - Avoid DML on the same object: Performing DML on the same object within a before trigger can cause recursion, where the trigger keeps firing repeatedly.
- Use after triggers for related objects: If you need to perform DML on related objects (e.g., creating a child record when a parent is updated), do this in an after trigger.
Example:
- Good:
trigger AccountBeforeUpdate on Account (before update) {
for (Account acc : Trigger.new) {
if (acc.AnnualRevenue == null) {
acc.AnnualRevenue = 0;
}
}
}
- Bad:
trigger AccountBeforeUpdate on Account (before update) {
for (Account acc : Trigger.new) {
update acc; // This is not recommended and can cause recursion
}
}
Summary:
- Only modify the records in
Trigger.new
in before triggers. Use after triggers for explicit DML operations on related objects.
7. How do you bulkify a trigger?
Answer:Â Bulkification is the process of designing your trigger logic to handle multiple records at once, rather than processing one record at a time. Salesforce can invoke triggers with up to 200 records in a single batch, so writing bulk-safe code is essential to avoid hitting governor limits and to ensure efficient processing.
Best Practices for Bulkification:
- Avoid DML and SOQL inside loops: Performing queries or DML operations inside a loop can quickly exceed Salesforce governor limits. Instead, collect all necessary data in collections (lists, sets, or maps) and perform operations outside the loop.
- Process all records inÂ
Trigger.new
 orÂTrigger.old
: Always iterate over the entire collection of records provided by the trigger context. - Use Maps for Efficient Lookups: When you need to relate records or perform lookups, use maps to store and retrieve data efficiently.
Example:
- Bulkified Approach:
trigger OpportunityTrigger on Opportunity (before update) {
Set<Id> accountIds = new Set<Id>();
for (Opportunity opp : Trigger.new) {
if (opp.AccountId != null) {
accountIds.add(opp.AccountId);
}
}
Map<Id, Account> accounts = new Map<Id, Account>([SELECT Id, Name FROM Account WHERE Id IN :accountIds]);
for (Opportunity opp : Trigger.new) {
if (accounts.containsKey(opp.AccountId)) {
// Perform logic using related Account
}
}
}
Summary:
- Always design triggers to handle bulk data. Test with more than 200 records to ensure your trigger is truly bulk-safe.
8. What is the order of execution in Salesforce?
Answer: The order of execution in Salesforce refers to the sequence of events that occur when a record is inserted, updated, or deleted. Understanding this order is crucial for writing reliable triggers and automation, as multiple processes can interact and affect data.
Key Steps in the Order of Execution:
- Load Original Record: The original record is loaded from the database (or initialized for new records).
- Apply System Validations: Salesforce applies basic field-level validations (e.g., required fields, data types).
- Execute Before Triggers: Any before triggers on the object are executed.
- Apply Custom Validations: Validation rules are evaluated.
- Save Record (Not Committed): The record is saved to the database, but not yet committed.
- Execute After Triggers: Any after triggers on the object are executed.
- Assignment Rules: Assignment rules (e.g., for leads or cases) are processed.
- Auto-Response Rules: Auto-response rules are processed.
- Workflow Rules: Workflow rules are evaluated and actions (field updates, tasks, emails) are queued.
- Processes and Flows: Process Builder and Flow automation are executed.
- Escalation Rules: Escalation rules are processed (for cases).
- Roll-up Summary Fields: Roll-up summary fields are updated.
- Parent Roll-up Triggers: If roll-up summary fields are updated, parent object triggers may fire.
- Post-commit Logic: Email notifications, asynchronous operations (e.g., @future methods, queueable jobs), and other post-commit logic are executed.
- Commit to Database: The transaction is committed to the database.
Best Practice:
- Be aware of this order when designing triggers and automation to avoid conflicts and ensure data integrity.
9. What's the difference between triggers and workflows/process builder/Flow?
Answer: Salesforce provides several tools for automating business processes, each with its own strengths and use cases. Understanding the differences helps you choose the right tool for the job.
FeatureTriggerWorkflowProcess BuilderFlowCode requiredYesNoNoNoComplex logicYesNoModerateYesOrder controlYesNoNoPartialRelated object updateYesLimitedLimitedYesCross-object logicYesNoLimitedYesBulk processingYesYesYesYesError handlingAdvancedBasicModerateAdvanced
Triggers:
- Written in Apex code, allowing for complex logic, cross-object processing, and fine-grained control over execution order.
- Best for scenarios requiring custom validation, integration, or logic that cannot be achieved with declarative tools.
Workflow Rules:
- Point-and-click automation for simple field updates, email alerts, tasks, and outbound messages.
- Limited to a single object and simple logic.
Process Builder:
- More powerful than workflow rules, allowing for multi-step logic, related record updates, and calling flows.
- Still limited compared to Apex triggers for very complex scenarios.
Flow:
- Visual tool for building complex business processes, including user interactions, multi-object logic, and integrations.
- Can be invoked from buttons, processes, or even Apex code.
Best Practice:
- Use declarative tools (Workflow, Process Builder, Flow) whenever possible for maintainability.
- Use triggers only when business requirements cannot be met with clicks, or when advanced logic is needed.
10. How do you test a trigger in Salesforce?
Answer: Testing triggers is a critical part of Salesforce development. Salesforce requires at least 75% code coverage by tests before deploying Apex code to production, but you should aim for 100% coverage and robust test logic.
Best Practices for Testing Triggers:
- UseÂ
@isTest
 annotation: Mark your test classes and methods with@isTest
to indicate they are for testing purposes. - Create test data: Always create your own test data within the test class. Do not rely on existing data in the org.
- Test all trigger events: Cover all scenarios—insert, update, delete, undelete, and bulk operations (more than 200 records).
- UseÂ
Test.startTest()
 andÂTest.stopTest()
: These methods help you test asynchronous code and reset governor limits within your test method. - Assert outcomes: Use
System.assert
statements to verify that your trigger logic works as expected. - Test for negative scenarios: Ensure your trigger handles errors and edge cases gracefully.
Example:
@isTest
private class AccountTriggerTest {
@isTest static void testAccountInsert() {
Account acc = new Account(Name = 'Test Account');
insert acc;
// Assert logic here
}
@isTest static void testBulkUpdate() {
List<Account> accList = new List<Account>();
for (Integer i = 0; i < 300; i++) {
accList.add(new Account(Name = 'Bulk ' + i));
}
insert accList;
// Assert logic for bulk processing
}
}
Summary:
- Write comprehensive test classes to ensure your triggers are reliable, bulk-safe, and meet deployment requirements.
🧠Pro Tips for Interview Success
- Always write logic in handler classes, not directly in triggers.
- Avoid hardcoding IDs—use Custom Settings or Custom Metadata.
- Understand governor limits and how your trigger respects them.
- Be prepared to write a sample trigger during the interview.
📘 Sample Trigger Interview Exercise
Question: Write a trigger to prevent updating an Account's Industry
field if the Account's Type
is "Customer".
Answer:
trigger PreventIndustryChange on Account (before update) {
for (Account acc : Trigger.new) {
Account oldAcc = Trigger.oldMap.get(acc.Id);
if (acc.Type == 'Customer' && acc.Industry != oldAcc.Industry) {
acc.Industry.addError('Industry cannot be changed for Customer accounts.');
}
}
}
Try AI Mock Interviews on Skillora.ai 💬
Want to ace your Salesforce developer interview? Practice with Skillora.ai's AI-powered mock interview platform at https://skillora.ai/ai-interview. Our AI interviewer will simulate real interview scenarios and provide detailed feedback on your responses.
Key Benefits
- 🧠Get instant feedback on your technical knowledge and problem-solving approach
- 📋 Review your communication style and clarity of explanations
- 🎯 Access a comprehensive library of Salesforce developer questions at https://skillora.ai/questions
From trigger best practices to governor limits, our platform helps you prepare for all aspects of the Salesforce developer role. Start practicing today and boost your confidence for your next interview!
🎯 Conclusion
Mastering triggers is crucial for any Salesforce developer role. By understanding the concepts, context variables, best practices, and common pitfalls, you can confidently handle any trigger-related interview question.
Keep practicing real-world scenarios, and consider building your own trigger framework to solidify your understanding. Good luck with your Salesforce interviews!