Top 30 Salesforce CPQ Interview Questions & Answers
Thirty Salesforce CPQ interview questions with answers — quote-to-cash, products, bundles, price rules, product rules, approvals and contracts.
The latest Salesforce trigger interview questions — handler patterns, recursion control, bulkification and order of execution — with Apex examples.
If you're preparing for a Salesforce developer interview, one of the most crucial topics to master is Salesforce Triggers. Triggers are an essential part of Apex programming, enabling automation and enforcing business logic within Salesforce. Interviewers often test candidates on their understanding of trigger concepts, best practices, and real-world implementation scenarios.
In this blog, we will cover the latest and newly trending Salesforce Trigger interview questions, categorized based on concepts tested and why the question is asked. We will also provide the best way to respond as an interviewee to help you stand out as a knowledgeable and skilled candidate.
Concepts Tested
Why This is Asked
This question assesses whether the candidate has a foundational understanding of Triggers and their purpose in Salesforce development.
How to Answer
A Salesforce Trigger is an Apex code that executes before or after specific data manipulation events on a record. Triggers can be defined for standard and custom objects and are used to perform custom actions like validation, automation, or integration with external systems.
Example:
trigger AccountTrigger on Account (before insert, after update) {
if (Trigger.isBefore) {
// Perform actions before record insertion
} else if (Trigger.isAfter) {
// Perform actions after record update
}
}
Key Points to Mention
before and after events.Trigger.new, Trigger.old, Trigger.isInsert, etc., to access records and determine the event type.Concepts Tested
Why This is Asked
This question evaluates the candidate’s ability to work with Trigger context variables effectively, which is crucial for writing efficient and error-free Triggers.
How to Answer
Trigger context variables provide information about the current Trigger execution context. Some commonly used variables include:
Trigger.new: Contains the new version of records (available in insert and update events).Trigger.old: Contains the old version of records (available in update and delete events).Trigger.isBefore and Trigger.isAfter: Determine whether the Trigger is executing before or after the event.Trigger.isInsert, Trigger.isUpdate, etc.: Identify the type of event.Example:
trigger OpportunityTrigger on Opportunity (before update) {
for (Opportunity opp : Trigger.new) {
if (opp.Amount != Trigger.oldMap.get(opp.Id).Amount) {
opp.Description = 'Amount has been updated';
}
}
}
Key Points to Mention
Trigger.new and Trigger.old to compare old and new values.Trigger.new in after delete events, as the records no longer exist.Curious?
Following are the context variable available in triggers. Please note variable availability in trigger varies according to the type of trigger events.
| Variable | Usages |
|---|---|
| isExecuting | Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeAnonymous() API call. |
| isInsert | Returns true if this trigger was fired due to an insert operation. |
| isUpdate | Returns true if this trigger was fired due to an update operation. |
| isDelete | Returns true if this trigger was fired due to a delete operation. |
| isBefore | Returns true if this trigger was fired before any record was saved. |
| isAfter | Returns true if this trigger was fired after all records were saved. |
| isUndelete | If a record is recovered from the recycle bin, it returns true. |
| new | Returns a list of the new versions of the sObject records. This list is only available in insert, update, and undelete triggers, and the records can only be modified in before triggers. |
| newMap | A map of IDs to the new versions of the sObject records. This map is only available in before update, after insert, after update, and after undelete triggers. |
| old | Returns a list of the old versions of the sObject records. This list is only available in update and delete triggers. |
| oldMap | A map of IDs to the old versions of the sObject records. This map is only available in update and delete triggers. |
| size | The total number of records in a trigger invocation. |
Trigger.new and Trigger.newMap?Concepts Tested
Trigger.new and Trigger.newMap.Why This is Asked
This question tests your knowledge of Trigger context variables and their appropriate usage.
How to Answer
Trigger.new: A list of new versions of records (available in insert and update events).Trigger.newMap: A map of IDs to new versions of records (available in update events).Example:
trigger AccountTrigger on Account (after update) {
for (Id accId : Trigger.newMap.keySet()) {
Account newAcc = Trigger.newMap.get(accId);
Account oldAcc = Trigger.oldMap.get(accId);
if (newAcc.Phone != oldAcc.Phone) {
System.debug('Phone number updated for Account: ' + newAcc.Name);
}
}
}
Key Points to Mention
Trigger.new for iterating over records.Trigger.newMap when you need to access records by their IDs.Concepts Tested
Why This is Asked
This question tests the candidate’s ability to write scalable Triggers that can handle large volumes of data without hitting governor limits.
How to Answer
Bulkification is the process of writing Triggers that can handle multiple records at once. Salesforce processes records in batches, so Triggers must be designed to work efficiently with bulk data.
Example:
// Trigger definition: This trigger runs after a Contact record is inserted.
trigger ContactTrigger on Contact (after insert) {
// Create a list to store Account records that need to be updated.
List<Account> accountsToUpdate = new List<Account>();
// Loop through all the newly inserted Contact records in Trigger.new.
for (Contact con : Trigger.new) {
// Check if the Contact is associated with an Account (i.e., AccountId is not null).
if (con.AccountId != null) {
// Create a new Account record with the Id of the associated Account
// and update its Description field to 'Contact added'.
// Add this Account record to the accountsToUpdate list.
accountsToUpdate.add(new Account(Id = con.AccountId, Description = 'Contact added'));
}
}
// Check if there are any Account records in the accountsToUpdate list.
if (!accountsToUpdate.isEmpty()) {
// Update the Account records in the list.
// This will modify the Description field of the associated Accounts to 'Contact added'.
update accountsToUpdate;
}
}
Key Points to Mention
Example Scenario
Contact with AccountId = '001XXXXXXXXXXXX'.Account with Id = '001XXXXXXXXXXXX' will have its Description field updated to 'Contact added'.before and after Triggers?Concepts Tested
before and after Triggers.Why This is Asked
This question assesses whether the candidate understands when to use before vs. after Triggers based on the desired outcome.
How to Answer
Example:
trigger CaseTrigger on Case (before insert, after insert) {
if (Trigger.isBefore) {
// Set default priority before saving
for (Case c : Trigger.new) {
c.Priority = 'Medium';
}
} else if (Trigger.isAfter) {
// Send email notification after saving
for (Case c : Trigger.new) {
// Send email logic
}
}
}
Key Points to Mention
before Triggers for validation and modification.after Triggers for actions that require the record to be saved.Concepts Tested
Why This is Asked
This question evaluates the candidate’s ability to write Triggers that avoid recursion, which can lead to performance issues and governor limit exceptions.
How to Answer
Recursion occurs when a Trigger calls itself repeatedly, often due to updates within the Trigger. Use static variables to track whether the Trigger has already executed.
Example:
public class TriggerHelper {
public static Boolean isFirstRun = true;
}
trigger AccountTrigger on Account (before update) {
if (TriggerHelper.isFirstRun) {
TriggerHelper.isFirstRun = false;
for (Account acc : Trigger.new) {
acc.Name = acc.Name + ' Updated';
}
}
}
Key Points to Mention
before triggers instead of after triggers when updating the same object to avoid unnecessary DML operations.Concept of Trigger Recursion
Trigger recursion occurs when a trigger performs an action that causes the same trigger to fire again, creating an infinite loop. This can happen in scenarios like:
For example:
Contact object updates the Account object.Account object has a trigger that updates the Contact object.To prevent recursion, you can use a static variable to track whether the trigger has already executed. Static variables maintain their value across trigger executions within the same transaction, so they can be used to control re-entry.
Here’s an example of how to prevent recursion in a trigger on the Contact object:
// Static variable to track whether the trigger has already executed.
public class TriggerHelper {
public static Boolean isContactTriggerExecuted = false;
}
// Trigger definition: This trigger runs after a Contact record is inserted or updated.
trigger ContactTrigger on Contact (after insert, after update) {
// Check if the trigger has already executed in this transaction.
if (!TriggerHelper.isContactTriggerExecuted) {
// Set the static variable to true to prevent re-entry.
TriggerHelper.isContactTriggerExecuted = true;
// Create a list to store Account records that need to be updated.
List<Account> accountsToUpdate = new List<Account>();
// Loop through all the Contact records in Trigger.new.
for (Contact con : Trigger.new) {
// Check if the Contact is associated with an Account.
if (con.AccountId != null) {
// Update the Description field of the associated Account.
accountsToUpdate.add(new Account(Id = con.AccountId, Description = 'Contact updated'));
}
}
// Check if there are any Account records to update.
if (!accountsToUpdate.isEmpty()) {
// Update the Account records.
update accountsToUpdate;
}
}
}
TriggerHelper.isContactTriggerExecuted is a static variable that tracks whether the trigger has already executed.if (!TriggerHelper.isContactTriggerExecuted) condition ensures the trigger logic runs only if it hasn’t already executed in the current transaction.TriggerHelper.isContactTriggerExecuted = true; ensures that the trigger cannot re-enter itself.Description field of the associated Account records when a Contact is inserted or updated.Input
Contact with AccountId = '001XXXXXXXXXXXX'.Contact record.Output
Contact is inserted.Description field of the associated Account to 'Contact updated'.isContactTriggerExecuted is set to true.Contact is updated.isContactTriggerExecuted is true, the trigger logic is skipped, preventing recursion.Concepts Tested
Why This is Asked
This question assesses your ability to write efficient Triggers that can handle large datasets without hitting limits.
How to Answer
@future methods or Queueable Apex.Example:
trigger ContactTrigger on Contact (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact con : Trigger.new) {
accountIds.add(con.AccountId);
}
List<Account> accountsToUpdate = [SELECT Id FROM Account WHERE Id IN :accountIds];
// Perform updates on accountsToUpdate
}
Key Points to Mention
Concepts Tested
Why This is Asked
This question assesses the candidate’s ability to write efficient, maintainable, and scalable Triggers.
How to Answer
Example:
trigger OpportunityTrigger on Opportunity (after update) {
OpportunityHelper.updateRelatedAccounts(Trigger.new);
}
public class OpportunityHelper {
public static void updateRelatedAccounts(List<opportunity> opportunities) {
// Logic to update related accounts
}
}
Key Points to Mention
Concepts Tested
Why This is Asked
This question tests your ability to work with related records and perform complex updates.
How to Answer
Use SOQL queries to fetch related records and perform updates. Ensure bulkification to handle multiple records efficiently.
Example:
trigger OpportunityTrigger on Opportunity (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Opportunity opp : Trigger.new) {
accountIds.add(opp.AccountId);
}
List<account> accountsToUpdate = [SELECT Id, Total_Opportunities__c FROM Account WHERE Id IN :accountIds];
for (Account acc : accountsToUpdate) {
acc.Total_Opportunities__c = [SELECT COUNT() FROM Opportunity WHERE AccountId = :acc.Id];
}
update accountsToUpdate;
}
Key Points to Mention
Mind it!
Handling cross-object updates in Salesforce triggers involves updating related records in a different object when a record in the current object is inserted, updated, or deleted. This is a common requirement in Salesforce, such as updating an Account record when a related Contact is inserted or updated.
Requirement :
When aContactis inserted or updated, update theDescriptionfield of the relatedAccountto indicate that a new contact has been added.
trigger ContactTrigger on Contact (after insert, after update) {
// Create a list to store Account records that need to be updated.
List<Account> accountsToUpdate = new List<Account>();
// Loop through all the Contact records in Trigger.new.
for (Contact con : Trigger.new) {
// Check if the Contact is associated with an Account.
if (con.AccountId != null) {
// Add the related Account to the update list.
accountsToUpdate.add(new Account(
Id = con.AccountId, // Use the AccountId from the Contact.
Description = 'Contact added or updated: ' + con.FirstName
));
}
}
// Check if there are any Account records to update.
if (!accountsToUpdate.isEmpty()) {
// Perform a single DML operation to update all Account records.
update accountsToUpdate;
}
}
Contact with AccountId = '001XXXXXXXXXXXX'.Description field of the related Account is updated to: "Contact added or updated: [Contact FirstName]".FirstName of the same Contact.Description field of the related Account is updated again to reflect the new Contact name.Concepts Tested
addError() method.Why This is Asked
This question evaluates your ability to prevent data inconsistencies and ensure a smooth user experience by handling errors effectively.
How to Answer
Use the addError() method to prevent invalid data from being saved and display custom error messages to users. Always handle exceptions gracefully and log errors for debugging.
Example:
trigger OpportunityTrigger on Opportunity (before insert) {
for (Opportunity opp : Trigger.new) {
if (opp.Amount <= 0) {
opp.addError('Amount must be greater than zero.');
}
}
}
Key Points to Mention
addError() in before Triggers to prevent invalid data from being saved.System.debug() or a custom logging framework.after Triggers, as they can’t be caught and will cause the transaction to fail.before delete and after delete Triggers?Concepts Tested
before delete and after delete Triggers.Why This is Asked
This question assesses your ability to choose the right Trigger timing based on the desired outcome.
How to Answer
Example:
trigger AccountTrigger on Account (before delete, after delete) {
if (Trigger.isBefore) {
for (Account acc : Trigger.old) {
if (acc.Industry == 'Banking') {
acc.addError('Banking accounts cannot be deleted.');
}
}
} else if (Trigger.isAfter) {
// Log deletion in a custom object
}
}
Key Points to Mention
before delete for validation.after delete for post-deletion actions.Concepts Tested
Why This is Asked
This question evaluates your ability to work around Salesforce’s mixed DML limitations.
How to Answer
Mixed DML operations (e.g., updating a user and an account in the same transaction) are not allowed. Use @future methods or Queueable Apex to handle such scenarios.
Mixed DML occurs when you try to perform DML operations on both setup objects and non-setup objects in the same transaction. For example:
User (setup object) and updating an Account (non-setup object) in the same trigger.Example:
trigger AccountTrigger on Account (after update) {
Set<Id> userIds = new Set<Id>();
for (Account acc : Trigger.new) {
userIds.add(acc.OwnerId);
}
System.enqueueJob(new UpdateUserJob(userIds));
}
public class UpdateUserJob implements Queueable {
private Set<Id> userIds;
public UpdateUserJob(Set<Id> userIds) {
this.userIds = userIds;
}
public void execute(QueueableContext context) {
List<User> usersToUpdate = [SELECT Id FROM User WHERE Id IN :userIds];
// Perform updates on usersToUpdate
}
}
Key Points to Mention
Curious?
Handling mixed DML operations in Salesforce triggers can be challenging because Salesforce enforces strict restrictions on mixing setup objects (e.g., User, Profile, Group) and non-setup objects (e.g., Account, Contact, Opportunity) in the same transaction. This restriction exists to maintain data consistency and avoid deadlocks.
Salesforce enforces this restriction because:
To handle mixed DML operations, you can use one of the following approaches:
1. Use System.schedule() or @future Methods
@future or System.schedule().2. UseQueueableApex
Queueable Apex allows you to chain asynchronous jobs, making it easier to handle mixed DML operations.Example: Handling Mixed DML Using @future
Scenario:
When anAccountis inserted, create a newUserand update theAccountwith the newUser's ID.
trigger AccountTrigger on Account (after insert) {
for (Account acc : Trigger.new) {
// Call a future method to handle mixed DML.
createUserAndUpdateAccount(acc.Id);
}
}
public class AccountHandler {
@future
public static void createUserAndUpdateAccount(Id accountId) {
// Create a new User (setup object).
User newUser = new User(
FirstName = 'Test',
LastName = 'User',
Email = 'testuser@example.com',
Username = 'testuser@example.com' + System.now().getTime(),
Alias = 'tuser',
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
ProfileId = [SELECT Id FROM Profile WHERE Name = 'Standard User'].Id,
LanguageLocaleKey = 'en_US'
);
insert newUser;
// Update the Account (non-setup object) with the new User's ID.
Account acc = [SELECT Id, OwnerId FROM Account WHERE Id = :accountId];
acc.OwnerId = newUser.Id;
update acc;
}
}
@future method (createUserAndUpdateAccount) for each new Account.@future method performs the mixed DML operations in a separate transaction.User (setup object) and updates the Account (non-setup object) with the new User's ID.Output
Account is inserted, the trigger fires.@future method creates a new User and updates the Account with the new User's ID.Example: Handling Mixed DML Using Queueable Apex
Scenario:
When anAccountis inserted, create a newUserand update theAccountwith the newUser's ID.
trigger AccountTrigger on Account (after insert) {
for (Account acc : Trigger.new) {
// Enqueue a Queueable job to handle mixed DML.
System.enqueueJob(new CreateUserAndUpdateAccountQueueable(acc.Id));
}
}
public class CreateUserAndUpdateAccountQueueable implements Queueable {
private Id accountId;
public CreateUserAndUpdateAccountQueueable(Id accountId) {
this.accountId = accountId;
}
public void execute(QueueableContext context) {
// Create a new User (setup object).
User newUser = new User(
FirstName = 'Test',
LastName = 'User',
Email = 'testuser@example.com',
Username = 'testuser@example.com' + System.now().getTime(),
Alias = 'tuser',
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
ProfileId = [SELECT Id FROM Profile WHERE Name = 'Standard User'].Id,
LanguageLocaleKey = 'en_US'
);
insert newUser;
// Update the Account (non-setup object) with the new User's ID.
Account acc = [SELECT Id, OwnerId FROM Account WHERE Id = :accountId];
acc.OwnerId = newUser.Id;
update acc;
}
}
Queueable job (CreateUserAndUpdateAccountQueueable) for each new Account.execute method performs the mixed DML operations in a separate transaction.User (setup object) and updates the Account (non-setup object) with the new User's ID.Output
Account is inserted, the trigger fires.Queueable job creates a new User and updates the Account with the new User's ID.@future, Queueable, or platform events.Concepts Tested
Why This is Asked
This question tests your ability to translate business requirements into technical solutions.
How to Answer
Break down the business rules into smaller, manageable pieces and implement them using helper classes or methods. Ensure the Trigger is bulkified and handles all edge cases.
Example:
trigger OrderTrigger on Order (before insert) {
OrderHelper.validateOrders(Trigger.new);
}
public class OrderHelper {
public static void validateOrders(List<Order> orders) {
for (Order ord : orders) {
if (ord.TotalAmount > 10000 && ord.Status != 'Approved') {
ord.addError('Orders over $10,000 require approval.');
}
}
}
}
Key Points to Mention
Concepts Tested
Why This is Asked
This question evaluates the candidate’s ability to ensure Trigger functionality through comprehensive testing.
How to Answer
Write unit tests to cover all scenarios, including positive and negative cases. Use Test.startTest() and Test.stopTest() to isolate test logic and reset governor limits.
Example:
@isTest
public class AccountTriggerTest {
@isTest
static void testBeforeInsert() {
Account acc = new Account(Name = 'Test Account');
Test.startTest();
insert acc;
Test.stopTest();
acc = [SELECT Name FROM Account WHERE Id = :acc.Id];
System.assertEquals('Test Account', acc.Name);
}
}
Key Points to Mention
Concepts Tested
Why This is Asked
This question evaluates your ability to ensure Trigger performance and functionality under bulk conditions.
How to Answer
Create test data in bulk using loops and verify that the Trigger handles all records correctly.
Example:
@isTest
public class AccountTriggerTest {
@isTest
static void testBulkInsert() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Test Account ' + i));
}
Test.startTest();
insert accounts;
Test.stopTest();
System.assertEquals(200, [SELECT COUNT() FROM Account]);
}
}
Key Points to Mention
Concepts Tested
Why This is Asked
This question tests the candidate’s knowledge of the sequence in which Salesforce processes records, including validation rules, workflows, and Triggers.
How to Answer
The Salesforce order of execution includes the following steps:
before Triggers.after Triggers.Key Points to Mention
before Triggers run before validation rules.after Triggers run after validation but before the record is saved.Concepts Tested
Why This is Asked
This question evaluates your ability to write scalable and maintainable Triggers using frameworks.
How to Answer
Trigger frameworks provide a structured approach to writing Triggers, making them modular and reusable. Popular frameworks include the Handler Pattern and Trigger Dispatcher.
Example:
trigger AccountTrigger on Account (before insert, after insert) {
TriggerDispatcher.dispatch(Trigger.new, Trigger.oldMap, Trigger.operationType);
}
public class TriggerDispatcher {
public static void dispatch(List<SObject> newList, Map<Id, SObject> oldMap, System.TriggerOperation operation) {
switch on operation {
when BEFORE_INSERT {
AccountHandler.handleBeforeInsert(newList);
}
when AFTER_INSERT {
AccountHandler.handleAfterInsert(newList);
}
}
}
}
public class AccountHandler {
public static void handleBeforeInsert(List<Account> newList) {
// Logic for before insert
}
public static void handleAfterInsert(List<Account> newList) {
// Logic for after insert
}
}
Key Points to Mention
Salesforce Triggers are a powerful tool for automating business processes, but they require a deep understanding of best practices, governor limits, and the Salesforce platform. By mastering the concepts and questions covered in this blog, you’ll be well-prepared to tackle any Salesforce Trigger-related interview with confidence.
Remember, the key to success is not just knowing the answers but understanding the underlying concepts and being able to apply them in real-world scenarios. Happy coding, and best of luck with your Salesforce interviews!
Pro Tip: Stay updated with the latest Salesforce releases and features, as interview questions often reflect the newest trends and capabilities of the platform.
Mind it!
Facing interview is very stressful situation for everyone who want to get the job. For every problem there is a solution. Practice the best solution to crack the interview. Pick the best source and practice your technical and HR interview with experienced persons which helpful to boost confidence in real interview.
Related Posts
One short email when we publish something new — interview questions, Salesforce guides and career tips. No spam, unsubscribe in one click.
Thirty Salesforce CPQ interview questions with answers — quote-to-cash, products, bundles, price rules, product rules, approvals and contracts.
The 30 Salesforce Apex interview questions asked most — collections, SOQL, DML, governor limits, triggers, async Apex and testing — with answers.
Salesforce Headless 360 explained — what headless CRM means, how APIs and data cloud power it, and what it changes for developers and businesses.
Questions, corrections or your own experience — they all help the next reader.