Most commonly asked apex triggers in interviews
The triggers that I am sharing in this article are the most commonly asked in interviews. As per my experience , the most common scenario that I have faced in interviews is the first one. I have taken standard objects (Account, Contact, opportunity) for reference only. It can be any standard or custom objects having lookup detail relationship
- We have a lookup relationship between two objects. We want to count the number of child on a field on parent object. For example we have a field on Account as 'Number of Contacts', we want to count the number of contacts in that field. Write a trigger for the same.
There is a custom Field on Account - "Top Opportunity" which is lookup to opportunity. I want the Opportunity with maximum amount and stage = "Closed Won" to be populated on Account level from the list of opportunities within that account. Write a trigger
We want to calculate the sum of the Amount of all Opportunities on Account object. We have a field 'Sum of opportunities' on account object for the same. Write a trigger.
Trigger to prevent creation of a Contact with Duplicate Email(it can be any field as asked by interviewer) within Same account. For example, Account 'XYZ' can have only one contact as 'email@example.com', if user try to create one more contact with same email under this account, it should throw an error. Please note that any other account can have a contact with 'firstname.lastname@example.org' as email. It should be prevented under the same account only.
Note: It is important to follow the best practices while writing a trigger or class and it is indeed the most common interview question you will face.
Before referring any website to practice the trigger scenarios, make sure the best practices are followed as I have seen many websites where this is not followed.
Refer to the 'Improve your Apex code' in below module on trailhead for the best practices