0% found this document useful (0 votes)
105 views9 pages

Salesforce Trigger 5

Salesforce
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views9 pages

Salesforce Trigger 5

Salesforce
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Salesforce Apex and triggers Interview Questions

Here is a collection of interview questions with answers focused on Salesforce Apex,


Triggers, and Limits.

Apex Basics

1. What is Apex in Salesforce?


○ Answer: Apex is a strongly-typed, object-oriented programming language
developed by Salesforce that allows developers to execute flow and
transaction control statements on Salesforce servers in conjunction with calls
to the API. It’s similar to Java in syntax.
2. What is Governor Limits in Salesforce?
○ Answer: Governor Limits are runtime limits that are enforced by Salesforce to
ensure that code or processes don’t monopolize shared resources. These
limits include SOQL queries, DML statements, heap size, CPU time, and
more.
3. What are collections in Apex?
○ Answer: Collections in Apex include Lists, Sets, and Maps. Lists are ordered
collections, Sets are unordered collections of unique values, and Maps are
collections of key-value pairs.
4. What is the difference between a SOQL and a SOSL query?
○ Answer: SOQL (Salesforce Object Query Language) is used to fetch records
from a single object or multiple related objects. SOSL (Salesforce Object
Search Language) is used to perform text-based searches across multiple
objects.
5. What are DML statements in Apex?
○ Answer: DML (Data Manipulation Language) statements in Apex are used to
manipulate data in the database. Examples include insert, update,
delete, upsert, and merge.
6. Explain the purpose of the @future annotation.
○Answer: The @future annotation is used to run methods asynchronously. It
is often used for executing callouts to external services after a DML operation
or handling large volumes of data in a separate thread.
7. What are Custom Exceptions in Apex?
○ Answer: Custom Exceptions are user-defined exception classes in Apex,
allowing developers to define their own error-handling mechanisms beyond
the standard system exceptions.
8. What is the purpose of the Database class in Apex?
○ Answer: The Database class provides methods for performing DML
operations with more control, such as Database.insert and
Database.update. It also allows partial processing with the allOrNone
flag.
9. What are wrapper classes?
○Answer: Wrapper classes are custom classes that contain objects and
properties, often used to handle collections of different types in a single
collection. They help in creating complex data structures.
10. What is the with sharing keyword in Apex?
○ Answer: The with sharing keyword enforces sharing rules on the objects
that the class interacts with. It ensures that the code respects user
permissions and access rights.

Triggers

11. What is a Trigger in Salesforce?


○ Answer: A Trigger is an Apex code that executes before or after specific
database events on Salesforce records, such as before insert, after
insert, before update, and so on.
12. What are Trigger Context Variables?
○ Answer: Trigger Context Variables are built-in variables in Apex that provide
context about the operation. Examples include Trigger.new,
Trigger.old, Trigger.isInsert, Trigger.isUpdate, and others.
13. What are different types of Triggers?
○ Answer: There are two types of triggers: Before triggers, which are used to
validate or modify values before saving, and After triggers, which are used to
access field values set by the system and to perform actions on related
records.
14. Explain Trigger.new and Trigger.old.
○ Answer: Trigger.new is a list of the new versions of records for insert
and update events, while Trigger.old is a list of the old versions of
records for update and delete events.
15. What is a Recursive Trigger?
○ Answer: A Recursive Trigger is a trigger that calls itself repeatedly due to
data changes caused by another trigger execution. Recursive triggers can
lead to infinite loops.
16. How can you prevent a Recursive Trigger?
○ Answer: You can prevent recursion by using a static Boolean variable in a
helper class to check if the trigger has already run, thus controlling its
execution flow.
17. What are Trigger Handler classes?
○ Answer: Trigger Handler classes are custom classes used to handle trigger
logic separately. This approach follows the “Single Responsibility Principle”
and allows code reusability, readability, and easier debugging.
18. What is the difference between Trigger.new and Trigger.newMap?
○ Answer: Trigger.new is a list of the new versions of records, while
Trigger.newMap is a map with the record IDs as keys and the records as
values. Trigger.newMap is available only in before update and after
update triggers.
19. How can you handle exceptions in Triggers?
○ Answer: Exceptions in triggers can be handled using try-catch blocks around
code that may throw exceptions. Custom exceptions can also be thrown for
specific error handling.
20. What are limitations on Trigger execution?
○ Answer: Triggers are subject to Governor Limits, including limitations on DML
statements, SOQL queries, and CPU time, as well as heap size limits.

Governor Limits

21. What is the SOQL Query Limit in Apex?


○ Answer: The limit is 100 SOQL queries per transaction for synchronous calls
and 200 for asynchronous calls.
22. What is the DML Statement Limit in Apex?
○ Answer: You can execute up to 150 DML statements per transaction.
23. What is the CPU Time Limit for Apex?
○ Answer: The CPU time limit for Apex code is 10 seconds for synchronous
transactions and 60 seconds for asynchronous transactions.
24. What is the Heap Size Limit?
○ Answer: The heap size limit is 6 MB for synchronous Apex and 12 MB for
asynchronous Apex.
25. What is the Maximum Batch Size in Salesforce?
○ Answer: The maximum batch size for batch Apex jobs is 200 records per
execution.
26. What is the maximum callout time in Salesforce?
○ Answer: The maximum timeout for callouts is 120 seconds.
27. How does the Limit class help with Governor Limits?
○ Answer: The Limit class provides methods like Limits.getQueries(),
Limits.getDMLStatements(), and others to check the current
consumption of resources within an Apex transaction.
28. What is the Email Limit for single and daily emails?
○ Answer: Salesforce allows up to 5,000 emails per day for single emails and
1,000 recipients per mass email.
29. What is the maximum number of records returned by a SOQL query?
○ Answer: SOQL queries can return a maximum of 50,000 records in a single
transaction.
30. What is the callout limit in Apex?
○ Answer: You can make up to 100 callouts in a single transaction.

Advanced Apex Concepts

31. What is a Batch Apex?


○ Answer: Batch Apex is used to process large volumes of records
asynchronously in batches of up to 200 records per execution, allowing
developers to handle governor limits.
32. What is a Queueable Apex?
○ Answer: Queueable Apex is an asynchronous Apex that allows chaining of
jobs and helps run jobs sequentially with better resource control.
33. What is the purpose of a Scheduled Apex?
○ Answer: Scheduled Apex allows developers to schedule an Apex class to run
at specific times to automate repetitive tasks.
34. How do you call a web service from Apex?
○ Answer: Web services are called using HTTP classes in Apex, like
HttpRequest, HttpResponse, and Http, to make callouts to external
services.
35. What are Platform Events in Salesforce?
○ Answer: Platform Events enable real-time integration and can trigger flows,
processes, and Apex triggers, facilitating asynchronous, event-driven
communication.

Apex Best Practices

36. Why is bulkification important in Apex?


○ Answer: Bulkification ensures code can handle large data volumes and avoid
governor limits. It’s crucial for writing efficient, scalable Apex code, especially
in triggers.
37. What is the Transient keyword used for?
○ Answer: Transient is used in Visualforce controllers to declare variables
whose values are not required during view state serialization, helping reduce
view state size.
38. What is the difference between @AuraEnabled and @InvocableMethod?
○ Answer: @AuraEnabled is used to make Apex methods accessible from
Lightning components, while @InvocableMethod allows methods to be
used in declarative tools like Process Builder and Flow.
39. How do you handle large data volumes in SOQL?
○ Answer: Use LIMIT, pagination with OFFSET, and FOR loops to handle
large data volumes effectively in SOQL queries.
40. What is the @TestVisible annotation?
○ Answer: @TestVisible allows developers to expose private variables or
methods to test classes, ensuring code coverage and testing for private Apex
members.

Interview Scenarios

41. How would you prevent an infinite loop in a trigger?


○ Answer: Use a static Boolean flag in a helper class to check and control
trigger execution, preventing it from running multiple times unnecessarily.
42. Explain the Database.SaveResult class.
○ Answer: The Database.SaveResult class contains information about the
success or failure of DML operations when using Database.insert or
Database.update with allOrNone=false.
43. Describe the @isTest annotation.
○ Answer: The @isTest annotation marks an Apex class or method as a test
class/method. Only test classes are executed in test environments, helping
ensure coverage for deployment.
44. What is SOQL for loop?
○ Answer: The SOQL FOR loop is used to retrieve records in batches of 200,
improving performance and reducing memory usage when processing large
volumes of data.
45. How would you optimize code that frequently runs out of governor limits?
○ Answer: Review the code for efficient SOQL and DML usage, bulkify triggers,
use asynchronous processing where possible, and leverage the Limit class
to monitor limits.
46. What are Custom Metadata Types?
○ Answer: Custom Metadata Types allow developers to define custom data
types and build metadata records to store application configuration,
simplifying maintenance and portability.
47. How does Batch Apex handle large data volumes differently from triggers?
○ Answer: Batch Apex processes data asynchronously in chunks (batches) of
up to 200 records, avoiding governor limits more effectively than synchronous
triggers.
48. Explain Asynchronous Apex in Salesforce.
○ Answer: Asynchronous Apex, such as Batch, Queueable, and Scheduled
Apex, allows operations to run in the background, enabling large data
processing and efficient handling of callouts.
49. What are Custom Labels in Salesforce?
○ Answer: Custom Labels are custom text values that can be referenced from
Apex or Visualforce pages and can be used to support multi-language
capabilities.
50. How do you monitor or debug Apex execution?
○ Answer: Use debug logs, system debug statements, and tools like the
Developer Console to monitor and debug Apex code execution.
Real-Time Scenario-Based Questions

1. Scenario: Your client wants to ensure that any Opportunity with an amount greater
than $1,000,000 automatically sends a notification to the sales manager. How would
you implement this?
○ Answer: I would create a trigger on the Opportunity object for the before
insert and before update events. In the trigger, I’d check if the
Opportunity Amount is greater than $1,000,000. If true, I’d use the
Messaging class to send an email notification to the sales manager, or
alternatively, create a Task record assigned to the manager.
2. Scenario: You need to ensure that duplicate Account records are not created. What
approach would you use to prevent duplication?
○ Answer: To prevent duplicates, I’d use a before insert trigger on the
Account object. The trigger would query existing Account records based on
unique fields (e.g., Account Name or Account Number). If a match is found,
the trigger would throw a CustomException to prevent insertion. Another
approach would be to leverage Duplicate Rules and Matching Rules within
Salesforce for declarative prevention of duplicates.
3. Scenario: A custom field on the Contact object, Total_Purchase__c, should
always reflect the total amount of all related Opportunities. How would you ensure
this is updated in real time?
○ Answer: I’d create an after insert, after update, and after
delete trigger on the Opportunity object. In the trigger, I’d aggregate the
total amount of related Opportunities for each Contact and update the
Total_Purchase__c field. To optimize performance, I’d use Map<Id,
Decimal> to store and update the total for each Contact.
4. Scenario: Your company wants to archive old data. Any Case records older than a
year should be moved to a custom Archive object and deleted from the original. How
would you handle this?
○ Answer: I would use Batch Apex to handle this large data operation. The
Batch Apex job would query all Case records older than a year, create
corresponding Archive records in a custom object, and then delete the
original Case records. Batch Apex is suitable for this as it allows processing in
chunks, making it governor-limit friendly.
5. Scenario: A user updates an Account's Industry field. You need to update all
related Contacts’ Industry__c field to match. What’s the best way to achieve this?
○ Answer: I’d write an after update trigger on the Account object. In the
trigger, I’d identify all Accounts where the Industry field has changed, and
then collect all related Contact IDs. Using a single bulk DML statement, I’d
update the Industry__c field on all related Contacts to match the Account’s
industry.
6. Scenario: Your organization has a requirement to calculate and store the total value
of all Opportunities closed in the current fiscal year on the Account object. How would
you implement this?
○ Answer: I’d create a Roll-Up Summary field on the Account object if the
relationship between Account and Opportunity is Master-Detail. If it's a
Lookup relationship, I’d write a trigger on Opportunity that calculates the sum
of all Opportunities with a Closed Won stage in the current fiscal year and
updates a custom field on the Account object.
7. Scenario: You are asked to create a lead conversion process that automatically
creates an Account and a Contact without standard conversion, and links the
Account to a custom field on the Contact. How would you approach this?
○ Answer: I’d write an Apex method or trigger on the Lead object that checks
for a specific condition to identify leads ready for conversion. The method
would create Account and Contact records from Lead data and populate the
custom field on the Contact with the Account ID. The @future or Queueable
interface could also be used for asynchronous processing if needed.
8. Scenario: You need to prevent users from deleting records if they are associated
with active Contracts. How would you implement this?
○ Answer: I’d create a before delete trigger on the parent object to check
for active Contracts. If active Contracts are associated, I would add an error
message using addError() on the record, preventing deletion.
9. Scenario: Management wants to know if certain fields on Accounts and Contacts are
updated frequently. How would you track these updates?
○ Answer: I’d create a trigger on both Account and Contact for before
update events. This trigger would capture the old and new values of specific
fields, and if changes are detected, I would increment a custom counter field
or log details in a separate audit object. Alternatively, Field History Tracking
could be enabled if detailed tracking is needed.
10. Scenario: A customer wants to calculate discounts dynamically on Opportunity Line
Items based on quantity and product type. How would you handle this?
○ Answer: I’d write a trigger on the OpportunityLineItem object in before
insert and before update contexts. The trigger would apply the discount
based on conditions like quantity thresholds and product type, and update the
Discount__c custom field on the OpportunityLineItem. For complex
scenarios, I could use helper classes to handle different discount rules.

Apex Trigger Best Practices and Limits

11. Scenario: You have multiple triggers on the same object, leading to unexpected
behavior due to execution order. How would you handle this?
○ Answer: I would consolidate the triggers into a single trigger and use a trigger
handler framework. This structure allows better control over the order of
execution and separates logic by defining individual methods for each
operation.
12. Scenario: During a data load, you’re hitting Governor Limits on SOQL queries in a
trigger. What would you do to optimize it?
○ Answer: To optimize, I’d ensure all queries are outside loops and consolidate
queries into a single SOQL that returns all necessary records. I’d also
leverage Maps to store queried data and perform in-memory filtering,
reducing the need for repeated SOQL queries.
13. Scenario: Your Apex batch job fails due to exceeding the heap size limit. How would
you resolve this issue?
○ Answer: To manage heap size, I would streamline the batch’s execute()
method by processing smaller data chunks, using transient variables if
applicable, and removing any unused data from collections to release
memory. I’d also check if data could be processed incrementally or stored in
custom objects for later use.
14. Scenario: You’re asked to automate recalculating a large volume of records based
on specific criteria without affecting performance. What approach would you use?
○ Answer: I would use Batch Apex or Queueable Apex for asynchronous
processing. Batch Apex is suitable for recalculating large datasets because it
processes data in smaller chunks, preventing governor limits. Additionally, I
could schedule the batch job during off-peak hours to reduce the impact on
system performance.
15. Scenario: A business process requires sending 500+ custom emails in a single
transaction, but you're hitting governor limits. How would you handle this?
○ Answer: I’d break down the email sends by creating a batch Apex job that
sends emails in batches of 10 or fewer within the execute() method. If the
business logic allows, I’d schedule the batch job to run periodically, ensuring
all emails are sent without exceeding limits.

Complex Trigger and Apex Scenarios

16. Scenario: You need to prevent Opportunities with a Closed status from being
modified. How would you implement this?
○ Answer: I’d write a before update trigger on the Opportunity object that
checks the record’s current status. If the status is Closed, I’d use
addError() to prevent changes to the record.
17. Scenario: The business wants to automatically assign a Lead to the sales rep who
owns the related Account if a matching Account is found. How would you approach
this?
○ Answer: I’d create a before insert or before update trigger on Lead.
In the trigger, I’d query Accounts to check for matches based on Lead
information. If a match is found, I’d update the Lead’s OwnerId to the sales
rep associated with the Account.
18. Scenario: Management wants a daily summary email of new Leads and
Opportunities created the previous day. How would you achieve this?
○ Answer: I’d create a Scheduled Apex class that runs daily. The class would
query for Leads and Opportunities created within the last 24 hours, format the
data, and send an email summary using the Messaging class.
19. Scenario: You’re tasked with creating a discount approval process that triggers only
if a discount exceeds 20% on an Opportunity. What’s your approach?
○ Answer: I’d write a before insert and before update trigger on the
Opportunity object to check if the Discount__c field exceeds 20%. If it does,
I’d initiate the approval process by calling
Approval.ProcessSubmitRequest in the trigger.
20. Scenario: A client requests that any update to Contact's Email field should log the
old and new email addresses in a custom audit object. How would you implement
this?
○ Answer: I’d create an after update trigger on Contact. In the trigger, I’d
check if the Email field value has changed. If true, I’d create a new record in
the custom audit object with the old and new email values, along with the
timestamp and Contact ID for tracking.

These scenario-based questions test how well you can think through and implement
solutions in real Salesforce environments while respecting best practices and Governor
Limits. Preparing responses for these will showcase both technical skill and problem-solving
ability in your interviews.

You might also like