Latest Salesforce Interview Questions on Triggers (2025)

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.


1. What is a Salesforce Trigger, and how does it work?


Concepts Tested:

  • Basic understanding of Triggers.
  • Knowledge of Trigger events (before/after insert, update, delete, etc.).
  • Awareness of Trigger context variables.

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:

  • Triggers can be defined for before and after events.
  • Use Trigger context variables like Trigger.new, Trigger.old, Trigger.isInsert, etc., to access records and determine the event type.


2. What are Trigger context variables, and how do you use them?


Concepts Tested:

  • Understanding of Trigger context variables.
  • Practical application of these variables in real-world scenarios.

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:

  • Use Trigger.new and Trigger.old to compare old and new values.
  • Avoid using Trigger.new in after delete events, as the records no longer exist.

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.


3. What is the difference between Trigger.new and Trigger.newMap?


Concepts Tested:

  • Understanding of Trigger context collections.
  • Practical use cases for 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:

  • Use Trigger.new for iterating over records.
  • Use Trigger.newMap when you need to access records by their IDs.


4. How do you handle bulk records in a Trigger?


Concepts Tested:

  • Understanding of bulkification in Triggers.
  • Best practices for handling multiple records efficiently.

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:

  • Always use collections (e.g., Lists, Maps) to process records in bulk.
  • Avoid SOQL or DML operations inside loops to prevent hitting governor limits.

Example Scenario:

  • Input:
    • Insert a Contact with AccountId = '001XXXXXXXXXXXX'.
  • Output:
    • The Account with Id = '001XXXXXXXXXXXX' will have its Description field updated to 'Contact added'.



5. What is the difference between before and after Triggers?


Concepts Tested:

  • Understanding of Trigger timing.
  • Practical use cases for 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:

  • Before Triggers: Used to validate or modify records before they are saved to the database. For example, setting default values or validating field values.
  • After Triggers: Used to perform actions after records are saved to the database. For example, updating related records or sending notifications.

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:

  • Use before Triggers for validation and modification.
  • Use after Triggers for actions that require the record to be saved.


6. Can you explain the concept of Trigger recursion and how to prevent it?


Concepts Tested:

  • Understanding of recursion in Triggers.
  • Strategies to prevent infinite loops.

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:

  • Use static variables to control Trigger execution.
  • Avoid updates that re-trigger the same event.

Best Practices to Prevent Recursion

  1. Use static variables to track trigger execution.
  2. Avoid updating the same object in the trigger if possible.
  3. Use 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:

  1. Update in the Same Object: A trigger updates the same object it is defined on, causing the trigger to fire again.
  2. Related Object Updates: A trigger updates a related object, which in turn updates the original object, causing the trigger to fire again.

For example:

  • A trigger on the Contact object updates the Account object.
  • The Account object has a trigger that updates the Contact object.
  • This creates a loop where the triggers keep firing indefinitely.

How to Prevent Trigger Recursion

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.

Example Code: Preventing Recursion

Here’s an example of how to prevent recursion in a trigger on the Contact object:

Trigger Code

// 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;
        }
    }
}

Explanation of the Code

  1. Static Variable:
    • TriggerHelper.isContactTriggerExecuted is a static variable that tracks whether the trigger has already executed.
    • Static variables retain their value across trigger invocations within the same transaction.
  2. Check for Re-entry:
    • The if (!TriggerHelper.isContactTriggerExecuted) condition ensures the trigger logic runs only if it hasn’t already executed in the current transaction.
  3. Set Static Variable:
    • TriggerHelper.isContactTriggerExecuted = true; ensures that the trigger cannot re-enter itself.
  4. Trigger Logic:
    • The trigger updates the Description field of the associated Account records when a Contact is inserted or updated.

Example Scenario

Input:

  1. Insert a Contact with AccountId = '001XXXXXXXXXXXX'.
  2. Update the same Contact record.

Output:

  1. First Execution:
    • The trigger fires after the Contact is inserted.
    • It updates the Description field of the associated Account to 'Contact updated'.
    • The static variable isContactTriggerExecuted is set to true.
  2. Second Execution:
    • The trigger fires again after the Contact is updated.
    • However, since isContactTriggerExecuted is true, the trigger logic is skipped, preventing recursion.


7. How do you ensure Trigger performance in large data volumes?


Concepts Tested:

  • Performance optimization techniques.
  • Understanding of governor limits and scalability.

Why This is Asked:

This question assesses your ability to write efficient Triggers that can handle large datasets without hitting limits.

How to Answer:

  • Bulkify your Triggers: Process records in bulk using collections.
  • Avoid SOQL/DML in loops: Use maps and sets to store data and perform operations outside loops.
  • Use asynchronous processing: Offload heavy logic to @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:

  • Optimize SOQL queries by filtering records using sets or maps.
  • Use asynchronous processing for time-consuming operations.


8. What are the best practices for writing Salesforce Triggers?


Concepts Tested:

  • Knowledge of Trigger best practices.
  • Understanding of governor limits and performance optimization.

Why This is Asked:

This question assesses the candidate’s ability to write efficient, maintainable, and scalable Triggers.

How to Answer:

  • Bulkify your Triggers: Always handle multiple records.
  • Avoid SOQL/DML in loops: Use collections to store data and perform operations outside loops.
  • Use Helper Classes: Move logic out of Triggers into separate classes for better readability and reusability.
  • Minimize Trigger Logic: Keep Triggers lightweight and delegate complex logic to other classes or methods.
  • Test Thoroughly: Write unit tests to cover all scenarios.

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:

  • Follow the Single Responsibility Principle (SRP) by separating concerns.
  • Write comprehensive test classes to ensure code coverage.


9. How do you handle cross-object updates in Triggers?


Concepts Tested:

  • Understanding of relationships between objects.
  • Ability to perform updates across related objects.

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:

  • Use relationships (e.g., lookup or master-detail) to fetch related records.
  • Ensure updates are bulkified to avoid governor limits.

 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.

Example Scenario

Requirement :
When a Contact is inserted or updated, update the Description field of the related Account to indicate that a new contact has been added.

Example Code: Cross-Object Update in a Trigger

Trigger Code

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;
    }
}

Output:


  1. Insert a Contact:
    • Insert a Contact with AccountId = '001XXXXXXXXXXXX'.
    • The Description field of the related Account is updated to: "Contact added or updated: [Contact FirstName]".
  2. Update a Contact:
    • Update the FirstName of the same Contact.
    • The Description field of the related Account is updated again to reflect the new Contact name.


10. How do you handle errors in Salesforce Triggers, and what are the best practices?


Concepts Tested:

  • Error handling in Triggers.
  • Use of addError() method.
  • Best practices for graceful error handling.

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:

  • Use addError() in before Triggers to prevent invalid data from being saved.
  • Log errors using System.debug() or a custom logging framework.
  • Avoid throwing exceptions in after Triggers, as they can’t be caught and will cause the transaction to fail.


11. What is the difference between before delete and after delete Triggers?


Concepts Tested:

  • Understanding of Trigger timing for delete events.
  • Practical use cases for 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:

  • Before Delete Triggers: Used to validate or prevent deletions.
  • After Delete Triggers: Used to perform actions after records are deleted, such as logging or updating related records.

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:

  • Use before delete for validation.
  • Use after delete for post-deletion actions.


12. How do you handle mixed DML operations in Triggers?


Concepts Tested:

  • Understanding of mixed DML restrictions.
  • Strategies to handle mixed DML operations.

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:

  • Inserting a 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:

  • Use asynchronous processing to handle mixed DML operations.
  • Avoid direct DML on setup and non-setup objects in the same transaction.

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.

Why Is Mixed DML Restricted?

Salesforce enforces this restriction because:

  1. Setup Objects are metadata and require special handling.
  2. Non-Setup Objects are regular data objects.
  3. Mixing them in the same transaction can lead to deadlocks or data inconsistencies.

How to Handle Mixed DML Operations

To handle mixed DML operations, you can use one of the following approaches:

1. Use System.schedule() or @future Methods

  • Split the DML operations into separate transactions using asynchronous methods like @future or System.schedule().
  • Perform DML on setup objects in one transaction and non-setup objects in another.

2. UseQueueableApex

  • Queueable Apex allows you to chain asynchronous jobs, making it easier to handle mixed DML operations.

3. Use Platform Events

  • Publish a platform event to handle one part of the operation asynchronously.

Example: Handling Mixed DML Using @future

Scenario:
When an Account is inserted, create a new User and update the Account with the new User's ID.

Trigger Code

trigger AccountTrigger on Account (after insert) {
    for (Account acc : Trigger.new) {
        // Call a future method to handle mixed DML.
        createUserAndUpdateAccount(acc.Id);
    }
}

Future Method

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;
    }
}

Explanation of the Code

  1. Trigger:
    • The trigger calls a @future method (createUserAndUpdateAccount) for each new Account.
  2. Future Method:
    • The @future method performs the mixed DML operations in a separate transaction.
    • It creates a new User (setup object) and updates the Account (non-setup object) with the new User's ID.

Output:

  1. When an Account is inserted, the trigger fires.
  2. The @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 an Account is inserted, create a new User and update the Account with the new User's ID.

Trigger Code

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));
    }
}

Queueable Class

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;
    }
}

Explanation of the Code

  1. Trigger:
    • The trigger enqueues a Queueable job (CreateUserAndUpdateAccountQueueable) for each new Account.
  2. Queueable Class:
    • The execute method performs the mixed DML operations in a separate transaction.
    • It creates a new User (setup object) and updates the Account (non-setup object) with the new User's ID.

Output:

  1. When an Account is inserted, the trigger fires.
  2. The Queueable job creates a new User and updates the Account with the new User's ID.

Key Points

  • Avoid Mixed DML in the Same Transaction: Use asynchronous methods like @future, Queueable, or platform events.
  • Separate Setup and Non-Setup DML: Perform DML on setup objects and non-setup objects in separate transactions.
  • Bulkify Your Code: Ensure your asynchronous methods can handle multiple records.


13. How do you write a Trigger to enforce complex business rules?


Concepts Tested:

  • Ability to implement complex logic in Triggers.
  • Understanding of business rule enforcement.

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:

  • Use helper classes to encapsulate complex logic.
  • Test all possible scenarios to ensure compliance with business rules.


14. How do you test Triggers in Salesforce?


Concepts Tested:

  • Knowledge of Apex testing best practices.
  • Ability to write unit tests for Triggers.

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:

  • Aim for at least 75% code coverage.
  • Test bulk scenarios and edge cases.


15. How do you test Triggers for bulk data scenarios?


Concepts Tested:

  • Knowledge of bulk testing techniques.
  • Ability to simulate large data volumes in tests.

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:

  • Use loops to create bulk test data.
  • Verify that the Trigger processes all records without errors.


16. Can you explain Trigger order of execution in Salesforce?


Concepts Tested:

  • Understanding of the Salesforce order of execution.
  • Awareness of how Triggers fit into the overall process.

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:

  1. Loads the original record from the database.
  2. Executes before Triggers.
  3. Runs validation rules.
  4. Executes after Triggers.
  5. Commits the record to the database.
  6. Executes post-commit logic like workflows and processes.

Key Points to Mention:

  • before Triggers run before validation rules.
  • after Triggers run after validation but before the record is saved.


17. How do you implement Trigger frameworks, and why are they important?


Concepts Tested:

  • Knowledge of Trigger frameworks.
  • Understanding of modular and reusable code.

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:

  • Use frameworks to separate concerns and improve code maintainability.
  • Follow best practices for modular and reusable code.


Conclusion

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.


Share This Post:

About The Author

Hey, my name is Saurabh Samir, and I am a Salesforce Developer with a passion for helping you elevate your knowledge in Salesforce, Lightning Web Components (LWC), Salesforce triggers, and Apex. I aim to simplify complex concepts and share valuable insights to enhance your Salesforce journey. Do comment below if you have any questions or feedback—I'd love to hear from you!