Top 50 Salesforce Trigger Interview Questions 2025

In this article, we’ll explore the most commonly asked Salesforce Trigger interview questions and answers.. Below are 50 essential Salesforce Trigger interview questions and detailed answers, reflecting real-world scenarios and best practices.​

1. What is a Trigger in Salesforce?

A Trigger in Salesforce is an Apex code block that executes before or after specific data manipulation language (DML) operations, such as insert, update, delete, or undelete, on Salesforce records. Triggers allow developers to perform custom actions like validation, updates, or integrations automatically. These are used for automating business processes, enforcing data integrity, and integrating with other systems.

2. What are the two types of triggers in Salesforce?

Salesforce supports two types of triggers:

  • Before Triggers: Execute before the data is saved to the database. Useful for validation or modifying record values before saving.
  • After Triggers: Execute after the data has been saved to the database. Ideal for operations that require the record ID, such as updating related records

3. What is the use of a trigger class in Salesforce?

A trigger class in Salesforce is a helper class that contains the business logic for triggers. By separating logic into a trigger class, developers can maintain cleaner code, enhance reusability, and simplify testing. This approach aligns with the Trigger Handler pattern, promoting modularity and scalability.

4. What Are the Different Events Available in Triggers?

In Salesforce, triggers can be set to execute custom logic in response to specific events in a record’s lifecycle. These events allow developers to run code either before or after a data manipulation operation occurs.

The available trigger events are:

  • before insert – Executes before a new record is saved to the database.
  • before update – Executes before an existing record is updated.
  • before delete – Executes before a record is deleted.
  • after insert – Executes after a new record has been saved.
  • after update – Executes after an existing record has been updated.
  • after delete – Executes after a record has been deleted.
  • after undelete – Executes after a record is restored from the Recycle Bin.

Each of these events gives developers the ability to control behavior, enforce business rules, and update related records during different phases of a DML operation.

5. When should we use a trigger or automation?

Triggers are suitable for complex logic that cannot be achieved through declarative tools such as Flow Builder . Use automation tools like Process Builder or Flow for straightforward tasks such as field updates or sending emails. Opt for triggers when dealing with bulk data operations, complex validations, or integrations that require custom logic.

6. Best practices and considerations for triggers?

Implement the following best practices:

  • Bulkify your code: Ensure your trigger can handle multiple records efficiently.
  • Use a single trigger per object: Avoid multiple triggers on the same object to prevent conflicts.
  • Delegate logic to handler classes: Keep triggers lightweight by moving business logic to separate classes.
  • Avoid hardcoding IDs: Use custom settings or custom metadata types for dynamic values.
  • Implement proper error handling: Use try-catch blocks to manage exceptions gracefully.

7.  How many times does the trigger execute on an Upsert event?

An Upsert operation can cause a trigger to execute multiple times:

  • Before Insert: If the record is new.
  • After Insert: If the record is new.
  • Before Update: If the record already exists and is being updated.
  • After Update: If the record already exists and is being updated.The exact number of executions depends on whether the record is new or existing and the specific fields being updated.

8. How many times does the trigger execute on a Merge event?

      During a merge operation:

  • Before Delete: On the losing record.
  • After Delete: On the losing record.
  • After Insert: On the winning record.

    Triggers on the losing record execute before those on the winning record.

9. Order of execution for triggers?

The Salesforce order of execution is as follows:

  • System Validation Rules
  • Before Triggers
  • Custom Validation Rules
  • Duplicate Rules
  • After Triggers
  • Assignment Rules
  • Auto-Response Rules
  • Workflow Rules
  • Escalation Rules
  • Roll-up Summary Fields
  • Criteria-Based Sharing Rules
  • Post-commit Logic

Understanding this sequence is crucial for ensuring data integrity and proper execution of business logic. For more detail you can click here for Salesforce official documentation.​

10. When would you choose a before event and when would you choose an after event?

Choose a before event when you need to validate or modify record values before they are saved to the database.
Opt for an after event when you need to perform actions that require the record ID or when dealing with related records.

11. What is the difference between Trigger.New and Trigger.NewMap?

Trigger.New is a list of the new versions of the sObject records being processed, while Trigger.NewMap is a map where the key is the record ID and the value is the new version of the record. Trigger.NewMap is particularly useful for comparing old and new values during update operations.

12. When should you use Trigger.Old?

We use Trigger.Old to access the previous versions of records during update or delete operations.

13. Can a Batch Job Be Called From a Trigger?

Yes, a batch job can be invoked from a trigger, especially when dealing with large volumes of data that might exceed governor limits. However, it’s essential to ensure that the batch job is called asynchronously to prevent delays in the trigger’s execution.

14. What Is the Trigger Handler Pattern?

The Trigger Handler pattern involves separating trigger logic into handler classes. This approach promotes cleaner, more maintainable code by delegating complex logic to dedicated classes, ensuring that the trigger itself remains concise and focused on execution flow.

15. How Do You Handle Bulk Operations in Triggers?

To handle bulk operations, it’s crucial to use collections like Lists, Sets, and Maps to gather records before performing DML operations. This approach ensures that the trigger can process multiple records efficiently without hitting governor limits.

16. What Is the Difference Between Trigger Context Variables and Static Variables?

Trigger context variables provide information about the trigger’s execution context, such as the records being processed and the type of operation (insert, update, delete). Static variables, on the other hand, are used to maintain state across trigger invocations, helping to manage scenarios like recursion.

17. How Do You Prevent Recursive Trigger Execution?

To prevent recursion, implement static boolean variables within the trigger handler class. By checking the value of this static variable, you can ensure that the trigger logic executes only once per transaction, avoiding infinite loops.

18 .How do you prevent recursive trigger execution with example ?


Recursive triggers occur when a trigger causes itself to run again, often leading to infinite loops or hitting governor limits. To prevent this, you can use a static variable in an Apex class to ensure that the logic inside the trigger runs only once per transaction

Example:

public class TriggerControl {
    public static Boolean isFirstRun = true;
}

trigger AccountTrigger on Account (after update) {
    if(TriggerControl.isFirstRun) {
        TriggerControl.isFirstRun = false;

        // Trigger logic here
        List<Contact> contactsToUpdate = new List<Contact>();
        for(Account acc : Trigger.new) {
            if(acc.Name != Trigger.oldMap.get(acc.Id).Name) {
                for(Contact c : [SELECT Id, AccountId FROM Contact WHERE AccountId = :acc.Id]) {
                    c.Description = 'Account name was updated';
                    contactsToUpdate.add(c);
                }
            }
        }
        update contactsToUpdate;
    }
}

This approach ensures that even if updates within the trigger logic cause the trigger to fire again, the main logic will only execute once in that transaction.

19. What Are Some Limitations of Triggers in Salesforce?

Triggers have several limitations, including governor limits on CPU time, DML operations, and SOQL queries. They cannot be used to perform operations on non-setup objects. Understanding these limits is essential for designing efficient and effective trigger logic.

20. How Do You Ensure Your Triggers Are Secure and Respect User Access Permissions?

To ensure security and respect for user access permissions, always use the ‘with sharing’ keyword in your trigger handler classes. This ensures that the trigger logic adheres to the sharing rules and field-level security settings defined in Salesforce.

21. What Is the Difference Between a Trigger and a Workflow Rule?

A trigger is a piece of program code that executes before or after a record is inserted or updated, allowing for complex logic and DML operations. A workflow rule, on the other hand, is a declarative automation tool that performs actions like field updates or email alerts based on specified criteria.

22. How Do You Test Triggers in Salesforce?

Testing triggers involves writing Apex test classes that simulate various scenarios, including bulk operations and edge cases. Utilize the @isTest annotation, Test.startTest(), and Test.stopTest() methods to manage governor limits and ensure comprehensive test coverage.

23. What Is the Difference Between Before and After Triggers?

Before triggers execute before the record is saved to the database, allowing for validation or modification of field values.
After triggers execute after the record is saved, enabling actions that require the record’s ID or interactions with related records.

24. How Do You Handle Callouts in Triggers?

Since triggers must execute synchronously, direct callouts are not allowed. To handle callouts, use asynchronous methods like @future or Queueable Apex to perform the callouts outside the trigger’s execution context.

25. What Is the Purpose of Using Custom Metadata Types in Triggers?

Custom Metadata Types allow you to store configuration data that can be accessed in Apex code. Using them in triggers helps avoid hardcoding values, making your code more flexible and easier to maintain.

26. Can You Explain the Use of ” Trigger.isBefore” and “Trigger.isAfter?

Trigger.isBefore returns true if the trigger is executed before the record is saved to the database, while
Trigger.isAfter returns true if the trigger is executed after the record is saved. These context variables help control the flow of logic within the trigger.

27. What Is the Role of Trigger.old and Trigger.new?

Trigger.old contains the old versions of the records before the DML operation, while Trigger.new contains the new versions after the DML operation. These context variables are essential for comparing changes during update operations.

28. How Do You Handle Errors in Triggers?

Error handling in triggers involves using try-catch blocks to catch exceptions and using the addError() method to display custom error messages on records. Additionally, consider using Database.rollback() to revert changes in case of errors.

29. What Is the Significance of addError() Method in a Trigger?

The addError() method is used in triggers to prevent a DML operation (like insert, update, or delete) from completing when specific business logic conditions are not met. This method is called on individual fields or records to display user-friendly error messages on the UI.

Example:

if(acc.AnnualRevenue < 1000){

acc.addError('Annual Revenue must be greater than 1000.');

}

This stops the record from being saved and notifies the user with the specified message. It’s a best practice to use addError() in before triggers for validations rather than allowing the record to save and then rolling back in after triggers.

30. What Is a Recursive Trigger? How Do You Prevent It?

A recursive trigger is when the execution of a trigger leads to the same trigger being invoked again, either directly or indirectly, causing an infinite loop. For example, if a trigger updates a record and that update causes the same trigger to fire again.

There are different ways to solve the recursion in the trigger.

  1. Use Static Boolean Variable
  2. Use Static Set to Store Record Id.
  3. Use Static Map
  4. Use Old Map
  5. Follow Best practice for triggers

Use a static Boolean variable in an Apex class to check if the trigger has already run.

Example:

public class TriggerHelper {

public static Boolean hasRun = false;

}

trigger AccountTrigger on Account (before update) {

if(TriggerHelper.hasRun == false) {

TriggerHelper.hasRun = true;

// trigger logic

}

}

This ensures the logic executes only once per transaction.

31. Can We Perform DML in a Before Trigger?

Yes, you can perform DML in a before trigger, but it’s not recommended. Since before triggers are executed before the record is saved to the database, making DML calls within them can lead to recursive calls or unnecessary usage of governor limits.

Instead of performing DML, you should directly modify field values in the trigger context variable (Trigger.new). For more complex operations, consider using an after trigger or delegate logic to asynchronous processes like Queueable Apex.

32. How Do You Handle Large Data Volumes in Triggers?

Handling large data volumes (LDV) in triggers requires following bulk-safe and governor-limit-aware patterns:

  1. Use collections (Lists, Maps, Sets) to process multiple records.

2. Avoid SOQL and DML operations inside for loops.

3. Break complex logic into helper classes

4. Consider using Batch Apex or Queueable Apex for post-trigger processing when hitting limits.

Example of bulk-safe trigger:


Set<Id> accountIds = new Set<Id>();
for(Contact c : Trigger.new){
accountIds.add(c.AccountId);
}
List<Account> accList = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];

33. Can Triggers Be Disabled Temporarily?

Salesforce does not offer a built-in method to disable triggers outright. However, you can design a mechanism using Custom Settings or Custom Metadata Types to conditionally bypass trigger logic based on configuration.

This approach is particularly useful in deployment scenarios, data loads, or testing environments where triggers may interfere with operations.

Example Using Custom Metadata Type:

if (TriggerControl__mdt.getInstance('AccountTrigger').IsActive__c) {
    // Execute trigger logic only if IsActive__c is true
    // Trigger operations go here
}

In this example, a Custom Metadata record named AccountTrigger includes a Boolean field “IsActive__c” . Administrators can toggle this field directly in the Salesforce UI to enable or disable trigger logic without modifying Apex code.

This method provides a flexible, declarative control layer over trigger execution and aligns with best practices for managing production environments.

34. What Is a Trigger Context Variable?

Trigger Context Variables in Salesforce are built-in variables that give information about the current context of a trigger. These variables allow developers to control logic depending on the trigger event (insert, update, delete, etc.) and whether the trigger is running before or after the database operation.

They are essential for writing dynamic and flexible trigger logic.

Key Trigger Context Variables:

  • Trigger.isInsert: Returns true if the trigger was fired due to an insert operation.
  • Trigger.isUpdate: Returns true if the trigger was fired due to an update operation.
  • Trigger.isDelete: Returns true if the trigger was fired due to a delete operation.
  • Trigger.isBefore: Returns true if the trigger is running before the data is saved to the database.
  • Trigger.isAfter: Returns true if the trigger is running after the data is saved to the database.
  • Trigger.new: Returns a list of the new versions of the sObjects.
  • Trigger.old: Returns a list of the old versions of the sObjects.
  • Trigger.newMap: A map of IDs to the new versions of the sObjects.
  • Trigger.oldMap: A map of IDs to the old versions of the sObjects.
  • Trigger.size: The total number of records in the trigger context.

Example: In a trigger on the Contact object, you can use Trigger.isUpdate to run logic only when a contact is updated, and Trigger.oldMap to compare the previous value of a field like Email.

35. What Happens if a Trigger Fails in Bulk DML Operation?

If one record in a bulk operation fails due to an error in a trigger, none of the records are committed unless the operation is done using Database.insert(records, false) which allows partial success.

Best Practice: Always handle exceptions using try-catch blocks and consider using Database.* methods to allow processing of valid records even if some fail.

36. What Are Recursive Triggers with Real-Time Example?

Suppose you have a trigger on the Account object that updates the related Contacts. If the Contact trigger, in turn, updates the related Account, this will create a recursive loop.

Real-world example:

Account Trigger updates Contact.

Contact Trigger updates Account → Account Trigger fires again → infinite loop!

Solution: Use static variables in a utility class to ensure logic runs only once.

37. How to Handle Roll-Up Summaries with Triggers?

When standard roll-up summary fields can’t be used ,such as when the relationship between objects is not masterdetail .You can use Apex triggers to manually calculate and update values.

Example: Count the number of active Contacts associated with an Account.

trigger ContactTrigger on Contact (after insert, after delete, after undelete) {
    Set<Id> accountIds = new Set<Id>();

    // Collect Account IDs from inserted or undeleted Contacts
    if (Trigger.isInsert || Trigger.isUndelete) {
        for (Contact c : Trigger.new) {
            if (c.AccountId != null) {
                accountIds.add(c.AccountId);
            }
        }
    }

    // Collect Account IDs from deleted Contacts
    if (Trigger.isDelete) {
        for (Contact c : Trigger.old) {
            if (c.AccountId != null) {
                accountIds.add(c.AccountId);
            }
        }
    }

    // Query related Accounts and their active Contacts
    List<Account> accList = [
        SELECT Id, Active_Contacts__c,
               (SELECT Id FROM Contacts WHERE IsActive__c = true)
        FROM Account
        WHERE Id IN :accountIds
    ];

    // Update the custom Active Contacts field with the count
    for (Account acc : accList) {
        acc.Active_Contacts__c = acc.Contacts.size();
    }

    update accList;
}

This logic ensures the Active_Contacts__c field on Account is updated based on the count of related Contacts marked as active.

38. Can a Trigger Call Another Trigger?

Yes, but indirectly. Triggers do not directly invoke other triggers. However, if a trigger on one object performs an operation (like an insert, update, or delete) on a second object that has its own trigger, then the second object’s trigger will automatically execute.

Example:

An Account trigger updates a related Contact. If the Contact object has its own trigger, it will run as a result of the update.

Be cautious with such designs to avoid unintended recursion and performance issues. Always use trigger frameworks or recursion guards where needed.

39. What Is Trigger.newMap and Trigger.oldMap?

Trigger.newMap provides a map of record IDs to the new versions of the records, and is available in before update, after update, and after delete triggers.

Trigger.oldMap provides a map of record IDs to the old versions of the records, and is available in before update, after update, and before delete triggers.

These maps are especially useful for comparing field values before and after a change, which helps in identifying what has been modified.

Example: Detecting if the Name field was changed during an update:

if (Trigger.isUpdate) {
    for (Id id : Trigger.newMap.keySet()) {
        Contact oldContact = Trigger.oldMap.get(id); // Get the old version
        Contact newContact = Trigger.newMap.get(id); // Get the new version

        // Check if the Name field has been modified
        if (oldContact.Name != newContact.Name) {
            // The Name field was updated
        }
    }
}

40. Can We Use Triggers to Call External Systems?

Direct callouts are not allowed in triggers. You need to use asynchronous processes like:

  • @future methods
  • Queueable Apex
  • Batch Apex

This decouples the trigger from the long-running HTTP request.

41. What Are Governor Limits in Salesforce Triggers?

Salesforce enforces strict governor limits to ensure resource fairness. Common limits include:

  • 100 SOQL queries per transaction
  • 150 DML operations per transaction
  • 50,000 records retrieved by SOQL
  • 10 callouts per transaction

Bulkification and best practices help stay within these limits. For more detail on limit you can check salesforce official documentation by clicking here .

42. What Is Trigger.size() Used For?

Trigger.size() returns the total number of records that fired the trigger. It’s particularly useful for bulk processing, logging purposes, or conditional logic based on the size of the data batch.

Example: Logging a message when more than 100 records are processed.

// Check if the trigger is processing more than 100 records
if (Trigger.size > 100) {
    System.debug('Processing more than 100 records');
    // Additional logic for handling large data volume can be added here
}

This approach helps developers distinguish between single-record and bulk-processing scenarios, allowing for more efficient and scalable trigger logic.

43. Can Triggers Be Used with Platform Events?

Yes. Triggers can be written on Platform Events just like on standard or custom objects. Platform Event triggers allow you to handle real-time, event-driven use cases.

Use Case Example: Writing a trigger on a Platform Event to process streaming data or integrate with external systems.

trigger PlatformEventTrigger on My_Custom_Event__e (after insert) {
    for (My_Custom_Event__e eventRecord : Trigger.new) {
        // Handle incoming event data
        // For example, create a record or update something
    }
}

This enables real-time processing within Salesforce in response to external system events.

44. What Is the “with sharing” Keyword and How Does It Affect Triggers?

The with sharing keyword in Apex ensures that your trigger logic respects sharing rules and user permissions. It is used in Apex classes (including those used by triggers) to enforce the current user’s access control.

By default, Apex runs in system mode, ignoring sharing rules. Using with sharing ensures that the logic respects record-level access based on the current user’s permissions.

Example:

public class AccountTriggerHandler with sharing {
    public static void handleAccountInsert(List<Account> accounts) {
        // Code here will only access records visible to the current user
    }
}

Using with sharing in a trigger handler class is important for maintaining data security and ensuring compliance with organization-wide data access policies.

45. How Do You Handle Record Locking in Triggers?

Record locking occurs when two or more transactions attempt to update the same record at the same time. In Salesforce, this can cause a “Record Locked” error, particularly in high-volume environments.

To manage and mitigate record locking, consider the following strategies:

  • Use FOR UPDATE in SOQL Queries: This explicitly locks the records during the current transaction, preventing other operations from modifying them simultaneously.
  • Implement Retry Logic: If a transaction fails due to a lock, retrying the operation (e.g., via Queueable Apex or Scheduled Jobs) can allow it to succeed after the lock is released.
  • Minimize DML on High-Contention Records: Avoid unnecessary updates to frequently accessed records to reduce the risk of locking.

Example Using FOR UPDATE:

List<Account> accountsToUpdate = [
    SELECT Id, Name
    FROM Account
    WHERE Id IN :accountIds
    FOR UPDATE
];

for (Account acc : accountsToUpdate) {
    acc.Name += ' - Updated';
}

update accountsToUpdate;

This code snippet ensures that the selected Account records are locked for the duration of the transaction, reducing the chance of simultaneous updates from other processes.licts.

46. What Are Some Common Real-World Scenarios for Triggers?

Here are some examples:

  • Automatically updating related records (e.g., when an Opportunity is closed, update the Account).
  • Validating data consistency across objects (e.g., prevent duplicate Contacts).
  • Performing custom roll-up summaries.
  • Triggering workflow or integrations with external APIs.
  • Maintaining audit trails or logging changes.

Summary  

This will help you to Prepare for Salesforce interview in 2025 to get a job . Please leave a comment if this article was helpful .

You can also check our related post for more Interview Related Question :

——————————————————————————————————————————————–

 


Discover more from Salesforce Hours

Subscribe to get the latest posts sent to your email.

1 thought on “Top 50 Salesforce Trigger Interview Questions 2025”

Leave a Comment