Salesforce Interview Questions on Triggers
A trigger is the piece of code, that is executed Before or After a record is inserted or updated.
Usually, an APEX (code) based evaluation of criteria to set off a chain of events.These events execute the following types of operations like : Insert, Update, Delete, Merge, Upsert and Undelete.
Hey Guys, In this post I am going to share Salesforce Interview Questions on Triggers
1. What is a Trigger?
The trigger is defined as an Apex code that execute before or after the following functions such as insert, update and delete etc. Trigger enables to perform custom actions before and after modifications to the records of Salesforce.
Types of Apex triggers
There are two types of triggers:
• Before trigger are used to update or validate values of a record before they are saved to the database.
• After trigger are used to access field values of the records that are stored in the database and use these values to make changes in other records.
The records that fire the after trigger are read only.
Trigger Syntax
trigger TriggerName on ObjectName (trigger_events) { // Implement the Logic here code_block }
Example:
trigger myAccountTrigger on Account (before insert, before update) { CreateAccount.getAccount(); }
MIND IT !
1. myAccountTrigger
– triggerName ( It is the name you would want to give your trigger).
2. Account
– Objectname (It is the object on which the action needs to be performed).
3. before insert, before update
– Trigger_events
Before insert
: When using this event, the code block gets executed before a new record is inserted.
Before update
: When you use this event, the code will get executed before a new record is updated in the object.
2. What are the various event on which a trigger can fire?
A trigger is a set of statement which can be executed on the following events. In above trigger events one or more of below events can be used with comma separated.
• before insert
• before update
• before delete
• after insert
• after update
• after delete
• after undelete
3. What are the considerations while implementing the Triggers?
Consider the following before implementing the triggers.
• Upsert trigger fires on 4 different events :- before(insert, update), after (insert, update)
• Merge trigger are fired on both events on delete
• Field history is updated after the trigger has successfully finished processing data.
• Any callout should be asynchronous so that trigger does not have to wait for the response.
• A trigger cannot have a static keyword in its code.
• If a trigger completes successfully the changes are committed to the database and if it fails the transaction is rolled back.
4. What are context variables in triggers?
When ever a trigger is invoked it has a group of supportive variables. Which hold runtime information during the current trigger execution and these variables are known as Trigger Context Variables (TCV).
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 trigger true. |
new | Returns a list of the new versions of the sObject records. This sObject list is only available in insert, update, and undelete triggers, and the records can only be modified 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 sObject list is only available in update and deletes triggers. |
oldMap | A map of IDs to the old versions of the sObject records. This map is only available in update and deletes triggers. |
size | The total number of records in a trigger invocation. |
5. What are the considerations while implementing the Trigger Context Variables
• trigger.new
and trigger.old
cannot be used in Apex DML operations.
• You can use an object to change its own field values using trigger.new
, but only in before triggers. In all after triggers, trigger.new
is not saved, so a runtime exception is thrown.
• trigger.old
is always read-only.
• You cannot delete trigger.new
.
6. How is Trigger.New Different from Trigger.newMap?
Trigger.New
variable returns the list of sObject which has invoked the trigger and Trigger.NewMap
returns the map of ID’s with the newly entered records (key & value pair). NewMap is only available in after insert, before and after the update and after undelete.
7. How is Trigger.new different from Trigger.old?
Trigger.New
variable returns the list of sObject which has invoked the trigger and Trigger.old
returns a list of the older versions of the records which have invoked the trigger.
Trigger.Old is only available in update and delete events.
8. Can a trigger call a batch class?
Yes, we can call a batch class in the trigger as we do in the normal apex code.
9. Can a trigger make a call to Apex callout method?
we can call a callout method in Apex Trigger but the only condition is that it has to be an asynchronous callout because the trigger flow cannot wait on the response received by the callout method.
10. What will you do if a method inside apex class need to be executed only when it is getting called from trigger?
We will use trigger.isexecuting
in apex class to check if the method inside apex class is getting called from trigger and will execute the method if getting called from trigger.
11. What is the use of trigger.isexecuting?
Suppose we have a method in apex class and we want this method to run only when the method is getting called from apex trigger than we can make use of trigger.isexecuting in apex class to check if the method is getting called from trigger.
12. Is the id of record changes if we undelete a deleted record?
No, It has the same id.
13. What is a Recursive Trigger?
A recursive trigger is one that performs an action, such as an update or insert, which invokes itself owing to, say something like an update it performs.
14. How to avoid Recursive Trigger?
Recursion occurs when some code is executed again and again. It can lead to infinite loop and which can result to governor limit some time. Some time it can also result is unexpected output.
To avoid recursive triggers you can create a class with a static Boolean variable with default value true. In the trigger, before executing your code keep a check that the variable is true or not. Once you check make the variable false.
Example 1:
Apex Class: checkRecursive.apxc
public Class checkRecursive{ private static boolean run = true; public static boolean runOnce(){ if(run){ run=false; return true; }else{ return run; } } }
Trigger Code: updateTrigger.apxt
trigger updateTrigger on anyObject(after update) { if(checkRecursive.runOnce()) { //write your code here } }
Example 2:
Scenario: There is an after update trigger on account object. In the trigger, there is a date field we are checking the date is changed or not if it is changed we are doing some process.The trigger is executed five times in the transaction.
In Recursive Trigger Handler Class, we have static variable which is set to true by default.
Apex Class: ContactTriggerHandler.apxc
public class ContactTriggerHandler { public static Boolean isFirstTime = true; }
Trigger Code: ContactTriggers.apxt
trigger ContactTriggers on Contact (after update) { Set accIdSet = new Set(); if(ContactTriggerHandler.isFirstTime) { ContactTriggerHandler.isFirstTime = false; for(Contact conObj : Trigger.New) { if(conObj.name != 'TEST') { accIdSet.add(conObj.accountId); } } // any code here } }
15. What do you mean by the bulkifying trigger?
By default, all triggers in Salesforce are bulky triggers. This means you can process many records simultaneously. Bulky triggers can handle bulk operations and single-record updates, such as the following :
• Data import
• Mass Fraction
• Bulk API calls
• The recursive apex methods
Note that
A trigger should be able to handle single record and thousands of record. There are two important point for it:
• Write triggers that operate on collections of sObjects.
• Write triggers that perform efficient SOQL and DML operations.
• If we will not follow above point we may hit governor limit when records are created/updated/deleted in mass using data loader or other tool.
16. Is there any limit on number of triggers define on an object?
We can define as many triggers on an object as we want but it is recommended to have one trigger per object because the order of execution of different trigger is not guaranteed and any trigger can fire first.
17. What is difference between Triggers and Workflow rules?
Triggers | Workflow |
---|---|
• Trigger is a piece of code that executes before or after a record is inserted or updated. |
• Workflow is automated process that fired an action based on Evaluation criteria and rule criteria. |
• Coding is required. |
• Coding is not required. |
• We can access the trigger across the object and related to that objects. |
• We can access a workflow across the object. |
• More than 15 DML operations can be used in a single trigger. |
• We cannot perform DML operation on workflow. Only insert and update. |
• We can use 20 SOQL’s from data base in one trigger. |
• We cannot query from database. |
18. What is limitations of Workflows overcome by Triggers in Salesforce
• Workflows are not able to create or update a separate object.
• You can’t reference certain fields when using workflows.
• You will not have your workflow doing more than just field updates and emails.
19. Difference between Validation rules and Triggers?
Validation Rules | Triggers |
---|---|
Validation rules are used to confirm that the data entered into a record meet various data quality / business rules before letting the user save it. |
Triggers can be used for various different things and can be executed at different times - e.g. when initiating a new record, before saving it, when a record is deleted. |
Validation rules are very easy to create and virtually anyone can learn how to create these. |
Triggers are more complex and generally require some development skills. |
20. Differences between a Stored Procedure and a Trigger?
1. We can execute a stored procedure whenever we want with the help of the exec command, but a trigger can only be executed whenever an event (insert, delete, and update) is fired on the table on which the trigger is defined.
2. We can call a stored procedure from inside another stored procedure but we can't directly call another trigger within a trigger. We can only achieve nesting of triggers in which the action (insert, delete, and update) defined within a trigger can initiate execution of another trigger defined on the same table or a different table.
3. Stored procedures can be scheduled through a job to execute on a predefined time, but we can't schedule a trigger.
4. Stored procedure can take input parameters, but we can't pass parameters as input to a trigger.
5. Stored procedures can return values but a trigger cannot return a value.
6. We can use Print commands inside a stored procedure for debugging purposes but we can't use print commands inside a trigger.
7. We can use transaction statements like begin transaction, commit transaction, and rollback inside a stored procedure but we can't use transaction statements inside a trigger.
8. We can call a stored procedure from the front end (.asp files, .aspx files, .ascx files, etc.) but we can't call a trigger from these files.
9. Stored procedures are used for performing tasks. Stored procedures are normally used for performing user specified tasks. They can have parameters and return multiple results sets.
10. The Triggers for auditing work: Triggers normally are used for auditing work. They can be used to trace the activities of table events.
21. Why Process Builder and how is it differ from trigger?
Process builder is fully customization. No code required here because we require lengthy logic and record to complete and fulfil the requirement or if we using process builder it will take less time to complete the requirement.
It has some benefits over the trigger:
SCENARIOS | OPTION | REASON |
---|---|---|
Scenario I
Populate a lookup field on record update: Traditionally required a trigger and It can be done easily with process builder. The issue is Multi layer lookup logic- i.e. multiple / nested maps of related data required in the trigger. |
Process builder
Trigger |
Traditionally been something that requires a Trigger. Process builder allows administrator can do this without the use of the code. |
Scenario II
Set an Account Owner based on Record criteria |
Process builder
Trigger |
Process builder can be used to assign ownership of records based on criteria in the object. |
Scenario III
Post a chatter message based on record criteria |
Process builder
Trigger |
Process builder can be used to post to chatter based on record criteria. |
Scenario IV
Submit a Quote for Approval when Opportunity Stage= Proposal |
Process builder
Trigger |
Requires 2 Processes one to Update the Quote based on the opportunity stage and another to submit the quote for the approval when the criteria on the quote had been met. |
Scenario V
Launch a Flow via record criteria vs a button or link. |
Process builder
Trigger |
Process builder can be used to set record criteria and then launch a trigger ready flow. |
Scenario VI
Clone an opportunity and change the field values |
Process builder
Trigger |
Although Process builder can create a new record it can’t reference any of the values from the cloned opportunity without the use of a flow to capture the opportunity values. |
22. What are the best practices for Triggers?
1. Write One-Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts.
2. Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.
3. Context-Specific Handler Methods
Using specific methods in your trigger-handler-class to keep your code clean and scalable.
4. Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.
5. Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception.
6. Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits.
7. Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore
8. Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found.
9. Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail.
10. Use a Framework
A framework! Why? It will make your code conform to the best practices, better testing, scalability and cleaner.
MIND IT !
• Follow proper naming conventions to make your code more logical and readable.
• Use trigger context-variables to identify specific event and performs tasks accordingly.
• Apex code must provide exception handling.
• Understand when to use before-trigger and when to user after-trigger.
23. What is the difference between database.insert and insert?
MIND IT !
insert
is the DML statement which is same as databse.insert
. However, database.insert
gives more flexibility like rollback, default assignment rules etc. We can achieve the database.insert
behaviour in insert by using the method setOptions(Database.DMLOptions).
Important Difference:
insert
• Partial insert is not supported.
• Roll back is not supported.
• If we use the DML statement (insert), then in bulk operation if error occurs, the execution will stop and Apex code throws an error which can be handled in try catch block.
Database.insert
• Database methods are static methods available in Database class.
• Partial insert is supported.
• Roll back is supported.
• If DML database methods (Database.insert) used, then if error occurs the remaining records will be inserted / updated means partial DML operation will be done.
Example: If you are inserting 10 records.
5 having all the required fields value and remaining 5 records missing required fields value.
In DML statement (insert) all the 10 records will be failed, because if one record is incorrect or error means all other remaining records will not be inserted. It will throw error.
In Database.insert 5 records will be inserted, remaining 5 records will be failed.(i.e. Partial DML Operation).
24. Can you explain the order of execution in Triggers?
The order of execution in Salesforce Triggers is crucial to understand to ensure that your code behaves as expected and avoids unexpected side effects. The order of execution can be broken down into several steps:
Record Identification: Salesforce identifies the records that are affected by the trigger (e.g., insert, update, delete, undelete).
Record Initialization: The system initializes the affected records. In before triggers, you can modify the record fields before they are saved to the database.
Before Triggers (Before Events): Before triggers are executed before the record is saved to the database. They are typically used for validation, field updates, or performing calculations based on the data.
Validation Rules: Salesforce runs validation rules to check if the record meets specific criteria. If any validation rule fails, the trigger execution is halted, and the user receives an error message.
Before Trigger (Before DML): This step is similar to step 3, but now the changes made to the records in before triggers are confirmed in memory.
Record Commit: The record is saved to the database.
After Triggers (After Events): After triggers are executed after the record is saved to the database. They are often used for tasks that require the record to be committed to the database, such as sending emails or creating related records.
Assignment Rules, Auto-Response Rules, Workflow Rules: These are executed after the record is committed to the database. They may update the record or trigger other processes.
Escalation Rules: If enabled, escalation rules are executed after the record is committed to the database.
Processes in Process Builder: Processes defined in Process Builder are executed after the record is committed to the database. They can perform various actions based on specified criteria.
Criteria-Based Sharing Rules: If applicable, Salesforce applies criteria-based sharing rules to determine the record's visibility to users.
Roll-up Summary Fields: Roll-up summary fields on the parent record are updated if there are child records related to the parent.
After Trigger (After DML): This step is similar to step 7, but now the changes made in after triggers are confirmed in memory.
Assignment Rules (Again): If applicable, Salesforce runs assignment rules again after the record is committed to the database.
Email Alerts: If configured, email alerts are sent.
Post-Commit Logic: Any logic that needs to be executed after the transaction is committed to the database (e.g., callouts to external systems) is performed here.
It's important to note that some steps may occur multiple times in the order of execution if there are nested triggers or if the trigger itself triggers other processes or workflows.
Understanding the order of execution in Salesforce Triggers helps developers design their code more effectively and anticipate how their changes may interact with other processes in the Salesforce environment. It also ensures that data integrity and consistency are maintained during database transactions.
Extra Knowledge !
Let's explain the order of execution in Salesforce Triggers using a simple example code.
Example Code:
Suppose we have two objects: `Account` and `Contact`. We want to create a trigger on the `Account` object that updates a custom field on the related `Contact` records whenever an `Account` is updated.
Record Identification:
Salesforce identifies the records that are affected by the trigger. For example, we update an `Account` record with Id `001XXXXXXXXXXXX`:
Record Initialization:
The system initializes the affected records. In this step, the `Account` record fields are available for modification in the before trigger.
trigger AccountTrigger on Account (before update) { for (Account acc : Trigger.new) { // Before record initialization - Trigger.new contains the new versions of records // You can modify the fields of the Account records here before they are saved to the database } }
Before Triggers (Before Events):
Before triggers are executed before the record is saved to the database. They are typically used for validation, field updates, or performing calculations based on the data.
trigger AccountTrigger on Account (before update) { for (Account acc : Trigger.new) { // Before trigger - modify fields or perform calculations before the record is saved acc.Custom_Field__c = 'Updated Value'; } }
Validation Rules:
Salesforce runs validation rules to check if the record meets specific criteria. If any validation rule fails, the trigger execution is halted, and the user receives an error message.
Before Trigger (Before DML):
This step is similar to the previous before trigger step, but now the changes made to the records in before triggers are confirmed in memory.
Record Commit:
The record is saved to the database.
trigger AccountTrigger on Account (before update) { for (Account acc : Trigger.new) { // Before trigger - modify fields or perform calculations before the record is saved acc.Custom_Field__c = 'Updated Value'; } // The modified Account records are committed to the database update Trigger.new; }
After Triggers (After Events):
After triggers are executed after the record is saved to the database. They are often used for tasks that require the record to be committed to the database, such as sending emails or creating related records.
trigger AccountTrigger on Account (after update) { for (Account acc : Trigger.new) { // After trigger - perform actions that require the record to be saved to the database List<contact> relatedContacts = [SELECT Id FROM Contact WHERE AccountId = :acc.Id]; for (Contact con : relatedContacts) { con.Custom_Field__c = 'Updated Value'; } update relatedContacts; } }
Assignment Rules, Auto-Response Rules, Workflow Rules:
These are executed after the record is committed to the database. They may update the record or trigger other processes.
Escalation Rules:
If enabled, escalation rules are executed after the record is committed to the database.
Processes in Process Builder:
Processes defined in Process Builder are executed after the record is committed to the database. They can perform various actions based on specified criteria.
Criteria-Based Sharing Rules:
If applicable, Salesforce applies criteria-based sharing rules to determine the record's visibility to users.
Roll-up Summary Fields:
Roll-up summary fields on the parent record are updated if there are child records related to the parent.
After Trigger (After DML):
This step is similar to the previous after trigger step, but now the changes made in after triggers are confirmed in memory.
Assignment Rules (Again):
If applicable, Salesforce runs assignment rules again after the record is committed to the database.
Email Alerts:
If configured, email alerts are sent.
Post-Commit Logic:
Any logic that needs to be executed after the transaction is committed to the database (e.g., callouts to external systems) is performed here.
MIND IT !
Understanding the order of execution in Salesforce Triggers helps developers design their code more effectively and anticipate how their changes may interact with other processes in the Salesforce environment. It also ensures that data integrity and consistency are maintained during database transactions.
Questions Based on Trigger Context Variables
MIND IT !
Hey guys, here i am sharing some questions based on Trigger Context Variables, which are very helpful in interviews.
i) What are the the context variable available with before insert event?
Only Trigger.new is available.
ii) What are the the context variable available with after insert event?
Trigger.new and Trigger.newMap.
iii) What are the the context variable available with before update event?
Trigger.new, Trigger.old, Trigger.newmap and Trigger.oldmap
iv) What are the the context variable available with after update event?
Trigger.new, Trigger.old, Trigger.newmap and Trigger.oldmap
v) What are the the context variable available with before delete event?
Trigger.old and Trigger.oldMap.
vi) What are the the context variable available with after delete event?
Trigger.old and Trigger.oldMap.
vii) What are the the context variable available with after undelete event?
Trigger.new and Trigger.newMap.
All the best
YOU CAN VISIT OTHER POST FROM OUR BLOG AS WELL,
(10) Comments
Thanks for Sharing :)
Thank you so much
Very well explained, Saurabh!
Appreciate!
I just like your content. Thanks for sharing.
Very useful contents!! Thanks for sharing..
THANK YOU
Awesome Que
Awesome que ans and concepts
Nice concept and well explained.
Thanks for the explanation