You are on page 1of 38

1. What Is Trigger In Salesforce?

Trigger is a procedure in database which automatically


invokes whenever a special events in Database occurs. Apex
triggers enable you to perform custom actions before or after
events to records in Salesforce, such as insertions, updates, or
deletions

Apex Triggers
2. What Are The Two Types Of Triggers In Salesforce?
There are two types of triggers in Salesforce.
 Before triggers are used to perform a task before a
record is inserted or updated or deleted in Salesforce.
These are used to update or validate record values before
they are saved to the database.
 After triggers are used if we want to use the information
set by Salesforce system and to make changes in the
other records. The records that fire the after trigger are
read-only.
3. What Is The Use Of Trigger Class In Salesforce?
Use the Trigger class to access run-time context
information in a trigger, such as the type of trigger or the list
of sObject records that the trigger operates on.
4. What Are Different Events Available In Triggers?
An Apex trigger is a set of the statement which can be
executed on the following events. We can add the below
events with comma-separated. Here is a list of trigger events
in Salesforce.

Trigger Events
5. When We Should Use Trigger Or Automation?
Use Salesforce flow for most of the automation in salesforce
and use Apex Trigger for complex logic which can’t be done
using Flow.
6. Best Practice And Consideration For Trigger?
Here is a list of all apex trigger best practices that we should
while creating the trigger in Salesforce.
1. One Trigger Per Object
2. Logic-less Triggers
3. Context-Specific Handler Method
4. Bulkify your Code
5. Avoid SOQL Queries or DML statements inside FOR
Loops
6. Using Collections, Streamlining Queries, and
Efficient For Loops
7. Querying Large Data Sets
8. Use @future Appropriately
9. Avoid Hardcoding IDs
7. How Many Times Trigger Execute On An Upsert Event
Upsert trigger fires on 4 different events :- before(insert,
update), after (insert, update)
8. How Many Times Trigger Execute On An Merge Event
Merge triggers are fired on both events on the delete.
9. Order Of Execution For Trigger
Check out our Order of execution in the Salesforce post on the
same.
10. When You Will Choose Before The Event And When
You Will Choose After The Event?
Use before the event to update the record which executes the
Apex Trigger. Use After the event to use related or child
records.
11. What Is The Difference Between Trigger.New And
Trigger.NewMap?
Trigger.New return the list of SObject which invoke the
trigger. Trigger.newMap return the Map of Id and SObject.
12. When We Should Use Trigger.Old?
It is always good and recommended to check the old and new
values before making any updates in Trigger. You can use
Trigger.Old to check the old value of the record. It can help
you to stop recursion in Trigger.
13. How To Void Recursion In Trigger?
There are different way to stop the recursion in Trigger
1. Use Static Boolean Variable: Create a class with a static
Boolean variable with a default value of true.
o This is good for less than 200 records.

o If we update 200+ records then it will only process

the first set of records and skip the others.


2. Use Static Set to Store Record Id: Use static set in class
to store all processed record IDs.
14. How Make Callout From Trigger?
No, we cannot. The callout is an Asynchronous process
whereas the Trigger is Dynamic / Synchronous. Callouts
would hold up the database transaction until the callout is
completed, which can be up to 120 seconds from a limited
perspective.
But using @Future annotation we can convert the Trigger into
an Asynchronous Class and we can use a Callout method.
Learn more about the future method in Salesforce.
15. Can We Call A Batch Job From Trigger?
Batch Apex can be invoked using an Apex trigger. But the
trigger should not add more batch jobs than the limit
16. What Is The Trigger Handler Pattern?
Please check this post to learn about Handler pattern and
code. Let us talk about what is the advantage of Trigger
Handler Patter.
1. Apex Class that handles trigger logic
2. Allows code to be called from other code or tests
3. Uses specific Trigger contexts and Trigger variables for
routing
4. Keep Triggers Simple
5. Allow for greater flexibility
6. Make code reusable
7. Unit tests are much easier
17. Have You Used Any Trigger Framework In Salesforce
Check out the apex hours Trigger Framework in the
Salesforce session for the same.
18. Difference Between Validation Rules And 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, or 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.

What is a Trigger?
Apex triggers enable you to perform custom actions before or
after events to records in Salesforce, such as insertions,
updates, or deletions. Just like database systems support
triggers, Apex provides trigger support for managing records.

Use triggers to perform tasks that can’t be done by using the


point-and-click tools in the Salesforce user interface. For
example, if validating a field value or updating a field on a
record, use validation rules and workflow rules instead.

What is Trigger Syntax?


1trigger TriggerName on ObjectName (trigger_events) {
2 code_block
3}
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
What are different type of Triggers?
There are two types of triggers:

 Before triggers are used to perform a task before a


record is inserted or updated or deleted. These are used
to update or validate record values before they are saved
to the database.
 After triggers are used if we want to use the information
set by Salesforce system and to make changes in the
other records. are used to access field values that are set
by the system (such as a record’s Id or Last Modified
Date field), and to affect changes in other records. The
records that fire the after trigger are read-only.
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.
Read the Apex Developer Guide for more detailed
considerations.

What are context variables in triggers?


All triggers define implicit variables that allow developers to
access run-time context. These variables are contained in
the System.Trigger class.

Following are the context variable available in triggers. Please


note variable availability in trigger varies according to the
type of trigger events.

 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, from the Salesforce user interface,
Apex, or the API.
 isUpdate: Returns true if this trigger was fired due to an
update operation, from the Salesforce user interface,
Apex, or the API.
 isDelete: Returns true if this trigger was fired due to a
delete operation, from the Salesforce user interface,
Apex, or the API.
 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: Returns true if this trigger was fired after a

record is recovered from the Recycle Bin (that is, after an


undelete operation from the Salesforce user interface,
Apex, or the API.)
 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 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 sObject 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,

both old and new.


Refer to Trigger context variables in salesforce link for more
details.
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. NewMap is only
available in after insert, before and after the update and after
undelete.

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

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.

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.

Define Recursive Trigger and how to avoid it?


There is a possibility that the result of the trigger can end up
calling the same trigger again and can run in a loop, this is
known as a recursive trigger. To avoid this scenario we should
create a static variable and check the value of this variable
before we execute anything in the trigger. For more details
refer to below link:

Avoid recursive trigger in salesforce


What do you mean by the bulkifying trigger?
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.

Bulk Apex Trigger trailhead

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.

Can you explain the order of execution in Triggers?


Following is the order of execution of events which
Salesforce perform before a DML Event.

1. The record is loaded from the database or is initialized in


case of upset statement.
2. New record’s field values are overwriting the old values,
now depending on the origin of the request this flow
varies: if the request is from a UI page then the following
validations are performed by Salesforce:
1. Any layout specific rules are checked
2. All the required values are checked at layout and
field level
3. All the field formats are validated along with the
maximum length of field values
If the request originates other than UI then Salesforce only
checks for Validation of foreign keys.

3. Now all the before triggers are executed at the database.


4. Most of the validations are performed again to verify that
all the required fields are holding some values and are
not null, at this step user defined validations are also
executed and the only validation which is not repeated in
this step are the rules specific to the layout.
5. After the success of the previous step, the record is
reviewed for duplicate records, by running the duplicate
rule. If a duplicate is found the flow is stopped and no
further actions performed.
6. In this step, record is saved to the database but it not
committed yet.
7. Now all the after Triggers are executed.
8. In this step, assignment rules are executed.
9. Now if there is any auto-response rule is present then
they are executed.
10. Next in the queues are the workflow, they are
executed after the auto response.
11. If the workflow was updating a field, then the fields
updated in this step and the flow after this step varies if
this was the case.
12. If a field was updated then the before and after
update triggers are fired once more and standard
validation are also executed again. Custom validation
escalation rule and duplicate rules are not required to run
again.
13. Once the execution has reached this stage, then
process is fired if there are any declared on the object.
14. Now the escalation rules are executed.
15. Entitlement rules are executed if any.
16. If there are any roll-up summary field, then they are
calculated at this step and the parent object go through
the save process.
17. Now the sharing rules are executed.
18. If we reach this stage, then that means no error has
occurred and the data is ready to be committed to the
database and is committed now.
19. Now if there is any post-commit logic like email,
then that is executed.
Can you explain some common use cases for using triggers
in Salesforce?

Triggers can be used for a number of different things, but


some of the most common use cases include:
– Automatically creating or updating records in Salesforce
based on changes in another system
– Enforcing data quality standards by validating data before it
is saved to Salesforce
– Sending notifications or emails based on changes in
Salesforce data
– Automatically assigning records to users or groups based on
certain criteria
4. Are there any limitations to the number of records that
can be updated by a single trigger execution? If yes, what
are they?

Yes, there are limits to the number of records that can be


updated by a single trigger execution. The limit is 100 records
for synchronous triggers, and 10,000 records for
asynchronous triggers.
5. What do you know about event handlers and Apex
CLASSES?

Event handlers are methods that are automatically called by


Salesforce when a specific event occurs, such as when a
record is created or updated. Apex classes are custom classes
that can be written in Salesforce’s Apex programming
language. Apex classes can be used to create event handlers.
6. What types of operations can be performed on multiple
objects in a single DML statement?

You can perform the following operations on multiple objects


in a single DML statement:
-Create
-Update
-Upsert
-Delete
You can also perform these operations on a single object, but
it is more efficient to perform them on multiple objects at the
same time.
7. Is it possible to execute code after inserting or updating
a record if no exceptions were thrown during the update
operation? If yes, how?

Yes, it is possible to execute code after inserting or updating a


record if no exceptions were thrown during the update
operation. This can be done by using the after update trigger.
8. Why should we avoid SOQL queries inside FOR loops?

One of the main reasons to avoid SOQL queries inside FOR


loops is because it can lead to governor limits being reached.
This can cause your code to fail and can cause performance
issues. Additionally, it can make your code more difficult to
read and maintain.
9. Can you explain what recursion is?

Recursion is a process where a function calls itself repeatedly


until a certain condition is met. In the context of a Salesforce
trigger, recursion can occur when a trigger fires and updates a
record, which then causes the trigger to fire again (since the
record has been updated). This can happen multiple times and
can eventually lead to an error if not handled properly.
10. What’s the best way to prevent recursive triggers from
executing more than once?

One way to prevent recursive triggers from executing more


than once is to use a static variable. When the trigger is fired,
the static variable is set to true. If the trigger is fired again
while the static variable is still true, then the trigger will not
execute.
11. What are the different ways of invoking Apex
methods?

There are four ways of invoking Apex methods: from a


Visualforce page, from an Apex controller or extension, from
a trigger, or from a class that implements an interface.

12. How does a trigger differ from a workflow rule?

A trigger is a piece of code that is executed automatically


when a record is inserted, updated, or deleted. A workflow
rule, on the other hand, is a set of conditions that are
automatically evaluated when a record is created or edited.
13. What happens when a callout is made to an external
web service while a trigger is being executed?

When a callout is made to an external web service while a


trigger is being executed, the trigger will pause execution until
the callout is complete. This can cause delays in the trigger
being executed, so it is important to take this into account
when designing triggers that make callouts.
14. What is a synchronous vs asynchronous callout?

A synchronous callout is one where the client (in this case,


Salesforce) waits for a response from the external service
before continuing. This means that if the external service is
down, or takes a long time to respond, then the client will be
unable to continue. An asynchronous callout is one where the
client does not wait for a response from the external service,
but instead continues on its own. This means that if the
external service is down, or takes a long time to respond, the
client will not be affected.
15. What type of exception can be thrown as part of a
trigger invocation?

A trigger can throw a System.Exception, which includes a


number of different types of exceptions, such as
DmlException, QueryException, and EmailException.
16. What is the difference between a trigger context
variable and a static variable?

A trigger context variable is a variable that is set by


Salesforce and is available to the trigger code. A static
variable is a variable that is set by the developer and is only
available within the scope of the trigger.
17. Can you give me an example of a situation where a
developer needs to write test code to ensure their trigger
functions correctly?

A developer would need to write test code to ensure their


trigger functions correctly if they were making changes to the
trigger that could potentially break its functionality. For
example, if a developer were changing the conditions under
which the trigger fired, they would need to write test code to
make sure that the trigger still fired when it was supposed to
and that it didn’t start firing when it wasn’t supposed to.
18. What is a Governor limit? Give me some examples of
governor limits.

A Governor limit is a limit placed on the amount of data or


number of records that can be processed by a Salesforce
trigger. This is done in order to prevent a trigger from
overloading the Salesforce system. Some examples of
governor limits include the maximum number of records that
can be processed by a trigger, the maximum number of
characters that can be processed by a trigger, and the
maximum number of DML statements that can be processed
by a trigger.
19. What are some use cases for writing batchable
processes in Salesforce?

Batchable processes can be used for a number of different


things, but they are typically used when you need to process a
large number of records at once. This could be something like
mass emailing a group of users or updating a large number of
records at once. Batchable processes can also be used to
schedule regular jobs, like nightly data backups or weekly
reports.
20. How would you determine if your trigger logic is
running efficiently or not?

One way to determine if your trigger logic is running


efficiently is to use the Salesforce Developer Console. The
Developer Console provides a “Debug Logs” feature that
allows you to monitor the execution of your trigger logic. If
you see that your trigger is taking a long time to execute, then
you can start to optimize your code to improve performance.
Q. What area unit totally different kind of Triggers?
Answer : There area unit 2 sorts of triggers:

Before triggers area unit wont to perform a task before a


record is inserted or updated or deleted. These area unit wont
to update or validate record values before they’re savedto the
info. once triggers area unit used if we would like to use the
knowledge set by Salesforce system and to create changes
within the different records. area unit wont to access field
values that area unit set by the system (such as a record’s Id or
LastModifiedDate field), and to have an effect on changes in
different records. The records that fireplace the once trigger
area unit read-only.

Q. Is there associatey limit on range of triggers outline on


an object?
Answer : We can outline as several triggers on associate
object as we would like however it’s counseled to possess one
trigger per object as a result of the order of execution of
various trigger isn’t guaranteed and any trigger will hearth
1st.This is one of the #1 trigger interview questions in
salesforce which was repeatedly asked in so many interviews

Q. What does one mean by the bulkifying trigger?


Answer : A trigger ought to be able to handle single record
and thousands of record. There area unit 2 necessary purpose
for it:

Write triggers that operate collections of sObjects.


Write triggers that perform economical SOQL and DML
operations.

If {we will|we’ll|we area unit going to} not follow on top of


purpose we have a tendency to might hit governor limit once
records are created/updated/deleted in mass exploitation
knowledge loader or different tool.

Q. Can a trigger decision a batch class?


Yes, we are able to decision a batch category within the
trigger as we have a tendency to kill the traditional apex code.
Q. Can a trigger create a decision to Apex callout method?
Answer : we can decision a callout technique in Apex Trigger
however the sole condition is that it’s to be associate
asynchronous callout as a result of the trigger flow cannot
attend the response received by the callout technique.

Q. Define algorithmic Trigger and the way to avoid it?


Answer : There is a break that the results of the trigger will
find yourself occupation a similar trigger once more and may
run in an exceedingly loop, this is often referred to as a
algorithmic trigger. To avoid this scenario we should always
produce a static variable and check the worth of this variable
before we have a tendency to execute something within the
trigger.

Q. How is Trigger.New totally different from


Trigger.newMap?
Answer : Trigger.New variable returns the list of sObject that
has invoked the trigger and Trigger.NewMap returns the map
of ID’s with the new entered records. NewMap is simply

available in once insert, before and once the update and once
undelete.
How is Trigger.new totally different from Trigger.old?

Trigger.New variable returns the list of sObject that has


invoked the trigger and Trigger.old returns an inventory of the
recenter versions of the records that have invoked the

trigger. Trigger.Old is simply out there in update and delete


events.
Q. What is limitations of Workflows overcome by Triggers
in Salesforce ?
Answer : The Limitations are Discussed Below

 Workflows aren’t able to produce or update a


separate object.
 You can’t reference bound fields once
exploitation workflows.
 You may not have your work flow doing quite
simply field updates and emails.

WHAT IS TRIGGER?

An Apex code that can execute specific data manipulation


language (DML) events before or after they occur, is called a
Trigger. There could be multiple events on which apex trigger
code can be executed.
TWO TYPES OF TRIGGERS
 Before triggers are used to update or validate record
values before they’re saved to the database.
 After triggers are used to access field values are set by
the system (such as a record’s Id or Last Modified Date
field) and to affect changes in other records, such as
logging into an audit table or firing asynchronous events
with a queue. The records that fire after the trigger is
read-only.
WHY TRIGGER FRAMEWORK/PATTERN?
Triggers are a powerful tool that can do great things when
used correctly but cause a lot of headaches when used
incorrectly. Triggers without structure can be messy. They can
interfere with one another and cause huge performance and
debugging problems.
Problems/Issue one can face if the trigger is not
written properly
o High possibility of causing recursion.

o Slow processing due to badly written code.

o The complexity of Unit Testing

o The maintenance of code is very difficult and

complex.
 Benefits of using Trigger Framework/Patterns.

o Generic code that can be extended based on

need/requirements.
o Reusable code.

o Saves time while writing test class.

o Enforce consistent trigger behavior.

o Easy to Maintain.

o Enforce best practices to be followed.

o Assure Order of execution.

o Makes Error Handling easy.

WHAT ARE DIFFERENT TRIGGER PATTERNS


AVAILABLE?
 Trigger Handler Pattern.
 Trigger Framework using a Virtual Class.
 Trigger Framework using an Interface.
 An architecture framework to handle triggers.
Here we will learn about Trigger Handler Pattern, its
advantage and disadvantage.
TRIGGER HANDLER PATTERN

DIAGRAM:

APEX TRIGGER:

TRIGGER HANDLER APEX CLASS:


ADVANTAGE OF TRIGGER HANDLER PATTERN:
 Apex Class that handles trigger logic
 Allows code to be called from other code or tests

 It uses specific Trigger contexts and Trigger variables for

routing purpose.
 Keep Triggers Simple and easy to understand

 Allow for greater flexibility

 Make code reusable

 Unit tests are much easier

LIMITATION OF TRIGGER HANDLER PATTERN:


 Still Repeated code
 Less code reusability
 Partial one trigger per object
BEST PRACTICE TO FOLLOW WHILE WRITING
TRIGGER
1) One Trigger Per Object
Always prefer to have one trigger per object. In case of
multiple triggers per object, you don’t have control over the
order of execution for triggers.
2) Logic-less Triggers
Avoid writing logic/method in the trigger. Logic/method
written inside trigger cannot be exposed to other class. Thus,
it decreased code reusability and not able to write test class
properly.
3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers
like afterInsertLogic, beforeInsertLogic etc.
4) Bulkify your Code
Always prefer to Bulkify your trigger code. It should work as
designated when there are more than one record.
5) Avoid using DML statements and SOQL Queries inside
FOR Loops
A single Apex transaction gets a maximum of 100 SOQL
queries before exceeding the governor limit. So, if the trigger
is invoked by a batch of more than 100 records, the governor
limit will throw a runtime exception. Also, try to query related
objects in one single query.
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 query more.
8) Use @future Appropriately
It is essential to write down your Apex code with efficiency
handle bulk or many records at a time. Use @fututre just in
case of a call out from trigger to make sure the current
transaction should not have to wait for a call out response.
9) Avoid Hardcoding IDs
When deploying Apex code between different environments
or Sandbox, or installing Force.com AppExchange packages,
it is essential to avoid hardcoding any kind of value such as
IDs in the Apex code. If possible, use custom label/custom
setting to store such hardcoded values.
10) Avoid calling batch from Trigger
When a batch is called from Trigger there are high chances to
hit the governor limit provided by Salesforce.

Q.1 What is Asynchronous Apex?


While working on the Salesforce application, we store huge
data in our org and it will keep growing year by year. If we
have to run some job that will take some time then in the case
of synchronous apex we will get the limit error, heap size
error, or timeout error. To avoid such issues, we can do those
long-running or time-consuming operations
using Asynchronous apex which will run in a separate thread
and will not impact the main thread. So Asynchronous Apex
is used to run the process in a separate thread at a later
time.
Q. 2 Where we can use Asynchronous Apex?
Asynchronous Apex can be used in long-running or time-
consuming operations like
 Sending Email to the user.

 Creating complex reports using Apex code

 Calling an external system for multiple records

 Schedule a job for a specific time

 Chaining apex code execution which might use API call

 Sharing Re-calculation

Q3. What are the benefits of Asynchronous processing?


Asynchronous process runs when the system is available for
operation. It is not blocking users from doing any work in the
application. This will give the below benefit to application.
 Increase User Efficiency

 More Heap Size and Higher Governer limit

 Better Scalability

Q.4 What are the types of Asynchronous Apex?


Currently, Salesforce supports four types of Asynchronous
Apex.
 Batch Apex
 Future methods
 Queueable Apex
 Scheduled Apex
Q.5 Within what timeframe will an asynchronous request
be processed after being enqueued?
Asynchronous processing has a lower priority than real-time
interaction via the browser and API. So it will always run in
the background when the resource is available to process
asynchronous jobs. We can not determine when the job will
run, it will be determined by the server. It can be immediate
also.
Q. 6 Can you make a web service callout from a trigger?
We cannot call external web services synchronously from
triggers, because calling a web service synchronously from
triggers will hold up the database transaction until the callout
is completed so we should use future methods to call external
web services.
Q. 7 Can a future method call another non-future method
to process tasks like callouts, and have those methods
return data to the future method for further processing?
No, we can not call future methods from the future method.
Q. 8 What are advantages of Batch Apex?
 Every batch transaction starts with a new set of governor

limits.
 The system itself divides the number of batches for

records
 If one batch fails, the other batches will continue to be

executed, and successful batches will still be committed


to the database. Successful batches are not rolled back
when one batch fails.
Q. 9 Why use Batch Apex in Salesforce instead of the
normal Apex?
There are various reasons why Batch Apex is better than
normal Apex.
 SOQL queries: Normal Apex uses 100 records per cycle
to execute SOQL queries. Whereas, Batch Apex does the
same in 200 records per cycle.
 Retrieval of SOQL queries: Normal Apex can retrieve

50,000 SOQL queries but, in Batch Apex, 50,000,000


SOQL queries can be retrieved.
 Heap size: Normal Apex has a heap size of 6 MB;

whereas, Batch Apex has a heap size of 12 MB.


 Errors: When executing bulk records, Normal Apex

classes are more vulnerable to encountering errors as


compared to Batch Apex.
Q. 10 What are some best practices when implementing
batch apex?
 Use normal Apex instead of Batch Apex when a small

number of records need to run.


 Use extreme care to invoke a batch job from a trigger.

The trigger should not add more batch jobs than the limit
 Methods declared as future aren’t allowed in classes that

implement the Database.Batchable interface.


 Methods declared as future can’t be called from a batch

Apex class.
 All methods in the class must be defined

as global or public.
 Minimize web service callout times.

 Tune queries used in batch Apex code.

 Minimize the number of asynchronous requests created

to minimize the chance of delays.


Q. 11 How many Schedulable Apex jobs can you have at
one time? In other words, what is the maximum number
of Apex classes that can be scheduled concurrently?
100 Schedulable Apex jobs can be scheduled.
Q. 12 Are synchronous web service callouts supported by
Scheduled Apex?
No. However, if Scheduled Apex calls a Batch Apex job
which then makes a web service callout, the callout will be
supported.
Q. 13 What are best practices for future methods?
 every future method invocation adds one request to the

asynchronous queue, avoid design patterns that add large


numbers of future requests over a short period of time.
 Ensure that future methods execute as fast as possible.

 If using Web service callouts, try to bundle all callouts

together from the same future method, rather than using a


separate future method for each callout.
 Consider using Batch Apex instead of future methods to

process a large number of records asynchronously.


Q. 14 Why sObject parameters not supported in future
methods?
The sObject might change between the time we call the
method and the time it executes that’s why sObjects can’t be
passed as arguments to future methods. In this case, the future
method will get the old sObject values and might overwrite
them.
Q. 15 Can I chain a job that has
implemented allowsCallouts from a Job that doesn’t have?
Yes, callouts are also allowed in chained queueable jobs.
Q. 16 Can I call Queueable from a batch?
Yes, But it is limited to just one System.enqueueJob call per
execute in the Database.Batchable class. Salesforce has
imposed this limitation to prevent explosive execution.
Q.17 In which scenario, we can’t call a future method
from a batch Job?
Calling a future method is not allowed in the Execute method,
But a web service can be called. A web service can also call
an @future method. So, we can define a web service having a
future method invocation and call the web service from the
execute method of Batch Job.
Q.18 How Future method helps in avoiding Mixed DML
errors?
There are 2 kinds of sObjects in salesforce.
1. Non-Setup: Account, opportunity, etc
2. Setup: User, groups,Queue etc
If we are performing DML on both kinds of sObject in a
single transaction, the system doesn’t allow it and throws an
exception called Mixed DML exception, stating that a
transaction can not have a Mixture of DML operation(Setup
and Non-Setup).
To resolve this error, we can put DML operations of a
particular kind in the Future scope. Since both the DML
operations are isolated from each other, the transaction
doesn’t fail.
Q.19 Let’s say, we have run an apex batch to process 2000
records, and It is running with batch size 200. Now, while
doing DML on 298th record, an error occurred, What will
happen in that case?
In batches, If the first transaction succeeds but the second
fails, the database updates made in the first transaction are not
rolled back.
Since the batch size is 200, so the first batch will be processed
completely and all data will be committed to DB. In seconds
batch, if we are committing records using normal DML
statements like insert, update then the whole batch will
be rollbacked. So records 201 to 400 will not be processed.
If we use the Database DML operations
like Database.insert with AllOrNone as false, then partial
commit can happen and only 298th record will not be
processed in that batch, and a total of 97 records will be
processed. Also, the other batch execution will not stop.
Q.20 What is Database.QueryLocator & Iterable<sObject>?
In Database.QueryLocator, we use a simple query
(SELECT) to generate the scope of objects. The governor
limit for the total number of records retrieved by SOQL
queries is bypassed, i.e. it can return up to 50 million records.
In Iterable<sObject>, we can create a custom scope for
processing, which would be not possible to create using
SOQL where clauses. the governor limit for the total number
of records retrieved by SOQL queries is still enforced.
1. What is difference between custom controller and
controller extension?
Ans.
custom controller:
Custom controller is required when standard controller is
not fitting a requirement Like if you need to some
custom validation or some external system call. We have
to implements all of the logic for a page without
leveraging a standard controller.controller extension:
controller extension extends the functionality of a
standard or custom controller. This is used when
1. When we want to override any action like edit, view
save or delete.
2. When we want to add new action
2. What is use of dynamic apex?
Ans.
There are number of use case of dynamic apex. Some of
them are
1. Showing record based on object selection on Page
2. Copy records into other object based on dynamic
configuration
3. How to find list of classes in org?
Ans.
We can use object ApexClass to get list of all Apex
Classes.
Select Id, name from ApexClass
4. How to find list of pages in Org?
Ans.
We can use object ApexPages to get list of all Apex
pages.
Select Id, name from ApexPage
5. How to find list of triggers in Org?
Ans.
We can use object ApexTrigger to get list of all Apex
trigger in org.
Select Id, name from ApexTrigger
6. Can we do overloading in Apex? If yes, how?
Ans.
Yes, we can do overloading in Apex. We can do
constructor and method
overloading. Overloading support in giving different
signature and implementation based on parameter.
7. public class OverloadExample {
8. integer height;
9.
10. //Constructor Overloading
11. public OverloadExample()
12. {
13. height=0;
14. }
15. public OverloadExample(integer xNum)
16. {
17. height=xNum;
18. }
19.
20. //Method Overloading
21. public integer getHeight(integer x)
22. {
23. return x*x;
24. }
25. public integer getHeight(integer x, integer y)
26. {
27. return x*y;
28. }
}
29. Why we have 15 and 18-character length record
id?
Ans.
15 Character length id is case sensitive and 18-character
id is case insensitive. Salesforce recommends to use 18-
character ID. Lightning is using 18-character Id to view
record page.We can remove last 3 character to get 15-
character Id.
30. Can we create Interface in Aped and How we
can use it?
Ans.
Yes, we can create interface in Apex.
31. interface IReqeuest {
32. string getRequestNumber();
33. }
34. public class CaseRequest implements IReqeuest
35. {
36. public string getRequestNumber()
37. {
38. // Give your implemenation
39. return '';
40. }
41. }
42.
43. How to retrieve record from recycle bin?
Ans.
We can use ALL Rows in SOQL.
SELECT COUNT() FROM Contact WHERE AccountId
= a.Id ALL ROWS
44. How can we lock record using SOQL so that it
cannot be modified by other user?
Ans.
For Update will lock record. Other user can not edit
after records are locked.
Account [] accts = [SELECT Id FROM Account LIMIT
2 FOR UPDATE];
Batch Apex
Batch Apex is used for long-running jobs with large data
volumes that need to be performed in batches, such as
database maintenance jobs. Batch Apex run over small
batches of records, covering our entire record set and breaking
the processing down to manageable chunks (a batch). Each
batch is considered a separate Apex transaction so that it will
not exceed the government limits while doing long-running
operations.
Limitations of Batch Apex
 Can have only 5 batch jobs running at a time.

 Execution may be delayed due to server/resource

availability.
 Future methods are not allowed.

 Future methods cannot be called from Batch Apex.

Queueable Apex
Queueable Apex can be used to run processes that will take a
long time, such as extensive database operations or external
web service callouts. Queueable Apex is a more advanced
and enhanced version of the future method with a few added
features which are mentioned below
1. Chaining jobs
2. Getting an Id for a job
3. Using non-primitive types
Limitations of Queueable Apex
 Queueable can’t handle millions of records in one job.
 Only one job can be scheduled at a time.

 In the developer edition stack depth for chaining the jobs

is limited to 5 including the parent job.


Reasons to use Queueable Apex over Batch Apex
 It is useful in operations that involve both Batch and
Future methods.
 Queueable apex can be called from the Future and Batch
class.
 In Queueable apex, we can chain up to 50 jobs and in
developer edition, we can chain up to 5 jobs only
whereas in Batch Apex 5 concurrent jobs are allowed to
run at a time.
 We can call a future method for executing long-running
operations, such as callouts to external web services or
other operations, on its own time as we can’t call future
methods from the batch class.
 Check out the blog Avoid Batch Apex and Use
Queueable Class to understand where we should use
Queueable instead of Batch Apex.
Reasons to use Batch Apex over Queueable
 It allows the processing of 50 million records in the

background
 Best suitable for long-running processes as it will create

chunks of records itself.

You might also like