KEMBAR78
Logic and Process Automation II PDF | PDF | Database Transaction | Class (Computer Programming)
0% found this document useful (0 votes)
263 views26 pages

Logic and Process Automation II PDF

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)
263 views26 pages

Logic and Process Automation II PDF

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/ 26

4/5/2020 Logic and Process Automation II – focusonforce.

com

TAKE NOTES

Previous Lesson Next Lesson


Logic and Process
CourseAutomation
Overview II (20%)

Objectives of this section

Demonstrate knowledge of the best practices for writing Apex triggers.

Describe the Apex features available for error handling and maintaining transactional integrity.

Identify the keywords used in a SOQL query and explain where they're used in a query's structure.

Demonstrate knowledge of the best practices for writing Apex triggers

After studying this topic, you should be able to:

Identify various best practices related to the use of Apex triggers

Identify examples of e cient and ine cient Apex triggers

Introduction

This topic discusses various best practices for creating Apex triggers in Salesforce. Creating ef cient Apex triggers is necessary to
ensure scalability and avoid exceeding the governor limits. This topic covers various examples of ef cient and inef cient Apex
triggers.

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 1/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

Apex Trigger Best Practices

There are several best practices related to the use of Apex Triggers in Salesforce:

1. Bulkify trigger code - The code de ned in an Apex trigger should be able to process a batch of records instead of one
record at a time. For example, if a trigger is invoked by a SOAP API call that inserts a batch of 200 records, all those records
should be processed as a bulk in the trigger to ensure scalability and avoid hitting governor limits.

2. Use SOQL query outside the for loop - Instead of placing a SOQL query inside a for loop to retrieve the data, a single
query should be used outside the for loop to retrieve all the necessary data, and then the for loop logic should iterate over the
results. This is to ensure that the trigger code does not reach the governor limit for the maximum number of SOQL queries that
can be executed in an Apex transaction.

3. Use DML statement to perform data manipulation - Instead of placing a DML statement inside a for loop to
perform operations such as insert, update, delete, and undelete, the records that need to be inserted or modi ed should be
added to a list, and a single DML statement should be invoked on that list after the execution of the for loop.

Ine cient Apex Trigger

E cient Apex Trigger

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 2/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

4. Use a bulki ed helper class - A helper class that is designed to process records in bulk should contain the logic of the
required operations. Methods of the helper class can be invoked to perform speci c operations in the trigger. The helper
methods should be written to handle collections of records, such as an array, list or set, instead of individual records.

5. Use queries and for loops ef ciently - The use of multiple SOQL queries to retrieve the records of a single object
should be avoided if a single query with multiple lters can be utilized. Also, the use of multiple for loops to loop through records
should be avoided, if a single for loop with if statements can be used instead.

6. De ne one trigger per object - If possible, only one trigger should be de ned per object to avoid redundancies and
inef ciencies. Since it is not possible to get explicit control over which trigger gets initiated rst, and each trigger that is invoked
does not get its own governor limits, it is better to create one trigger for all the possible DML events.

7. Use a SOQL for loop - If the total number of records that are returned by a SOQL query is likely to exceed 50,000, or the
query can cause the transaction to exceed the heap limit, a SOQL for loop should be used to process multiple batches of the
resulting records through the use of internal calls to query and queryMore. When a SOQL query is de ned in a for loop
de nition, the query results are chunked into batches of 200 records, and the for loop logic can be designed to handle those
individual batches.

Ine cient Apex Trigger

E cient Apex Trigger

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 3/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

Using a SOQL For Loop

8. Use the Limits Apex methods - Methods of the System class called ‘Limits’ should be used to output debug messages
for governor limits to determine if or when the code is about to exceed any governor limits. For example, Limits.getQueries() can
be used to retrieve the number of SOQL queries that have been used so far in the code, and Limits.getLimitQueries() can be used
to retrieve the total number of SOQL queries allowed.

Using the Limits Class

Execution Log

9. Use asynchronous Apex methods ef ciently - When designing triggers to utilize asynchronous Apex methods, it is
necessary to consider the governor limits speci c to methods with the @future annotation. One of the most important
considerations is that no more than 10 @future methods can be invoked from an Apex trigger. When using an @future method in
an Apex trigger, it is important to ensure that it is not placed in a ‘for’ loop and is invoked only once for all the records it needs to
process.

Invoking an @future method in an Apex Trigger

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 4/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

10. Design tests to verify bulk operations - Unit tests should be designed to verify that Apex triggers can handle large
datasets and not just single records. Test.startTest and Test.stopTest should be used to utilize a separate set of governor limits
wherever necessary. 

Testing an Apex Trigger

Learn More

"Apex Code Best Practices"

Describe the Apex features available for error handling and maintaining transactional integrity

After studying this topic, you should be able to:

Describe various ways of error handling in Apex

Explain how exception handling can be used to recover from error in code

Explain how to use different types of common built-in exceptions

List various common methods provided by Apex for exception handling

Explain how to create custom exceptions

Describe the considerations related to Visualforce and Bulk DML exceptions as well as mixed DML errors

Describe how Apex maintains transactional integrity

Introduction

This topic describes various Apex features that assist in error handling and maintaining the integrity of transactions. Exceptions
denote errors in code which can be handled using assertions, returning error codes, and exception handling. Built-in exception types
as well as custom exceptions can be utilized for exception handling. Multiple exceptions can be caught using the generic exception
type. Exceptions in custom controllers and controller extensions of Visualforce pages can also be handled. Apex ensures transactional Privacy - Terms

integrity by throwing exceptions and the execution of all the code before committing any database changes.
https://focusonforce.com/lessons/logic-and-process-automation-ii/ 5/26
4/5/2020 Logic and Process Automation II – focusonforce.com
integrity by throwing exceptions and the execution of all the code before committing any database changes.
TAKE NOTES

Exceptions

Exceptions denote errors and other events that disrupt the normal ow of Apex code execution.
An exception is thrown when Apex tries to execute code that is deemed impossible.

Different kinds of exceptions denote different types of errors.

Exceptions can be built-in or created for manual interruption of the program.


For example, an exception is thrown when the code expects a value from a variable that is null.

Unhandled Exceptions

If no code is written to deal with an exception that occurs, it is called an ‘unhandled exception’.

Code execution stops due to an unhandled exception, and any DML operations before the exception are rolled
back and not committed to the database.
Salesforce sends an email to the developer for an exception that is not caught by Apex code.
An error message appears in the Salesforce user interface when an end user runs into an unhandled exception.

Exceptions are logged in debug logs.

NullPointerException Example

Unhandled Exception Displays Error

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 6/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

Error Handling

Errors can be handled in Apex code using many ways, including assertions, returning error codes, and

exception handling.
Methods of the System class, such as assert() and assertEquals(), can be used to return a fatal error if a speci c
Boolean condition is not true or the value of two speci c arguments is different.
The Error class represents information about an error that occurred during a DML operation when using a
Database method.
The getMessage(), getFields(), and getStatusCode methods of Error class can be used to obtain error
information.
The addError() method of the SObject class can be used to mark a record with a custom error message and
prevent any DML operation.
Exceptions can be handled by using throw statements which are used to generate exceptions, while try, catch, and

nally statements are used to recover from exceptions.

assertEquals Method Example

Execute Anonymous Error

Exception Handling

Exceptions can be caught to gracefully recover from an error using the Try, Catch, Finally construct.

In the ‘try’ block, the block of code in which an exception can occur is included.

The ‘catch’ block is used to catch a speci c exception and includes exception handling code.

The optional ‘ nally’ block can be used to execute some code regardless of whether there an exception was thrown.
Multiple catch blocks can be used to catch different kinds of exceptions.
Exceptions related to exceeding governor limits cannot be caught.

Try, Catch, Finally Construct

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 7/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

Exception Handling Example

Execution Log

Built-In Exceptions

There are several built-in exceptions types provided by Apex.

Built-In exceptions are thrown by the runtime engine if errors are encountered in code execution.

In addition to the standard ‘exception’ class, there are several exceptions in the ‘System’ namespace.

There are several common exception methods which can be called by and operated on a particular instance of
an exception.
The getMessage() method can be used to return the error message associated with an exception that displays for the
user.

DML Exceptions

A DML exception can be used to catch any block of code that could result in an error due to a problem with a

DML statement.
The DML exception can be caught in the catch block using an argument of the ‘DmlException’ built-In exception
type.
For example, an insert DML statement that tries to insert a record without setting any of its required elds can be caught
using DmlException.

DmlException Example

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 8/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

Execution Log

List Exceptions

A list exception can be used to catch any block of code that could result in an error caused due to a problem

with a list, such as attempting to access an index that is out of bounds.


The list exception can be caught in the catch block using an argument of the ‘ListException’ built-in exception type.
For example, if a block of code tries to access two elements in a list that has only one, a list exception can be caught and a
related error message can be displayed.

ListException Example

Execution Log

Null Pointer Exceptions

A null pointer exception is used when there could be a problem with dereferencing a null variable.

The null pointer exception can be caught in the catch block by using an argument of the ‘NullPointerException’
built-in exception type.
For example, if the code tries to call a method on a variable which has been created but not initialized with a value, a
NullPointerException is thrown.

NullPointerException Example

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 9/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES
Execution Log

Query Exceptions

A query exception can be used when there could be a problem with a SOQL query in code, such as assigning a
query that returns no records.
The query exception can be caught in the catch block using an argument of the ‘QueryException’ built-in exception
type.
For example, if the value of a SOQL query that returns more than one record is assigned to a single sObject variable, a
QueryException is thrown.

QueryException Example

Execution Log

SObject Exceptions

Sobject Exceptions can be used to handle a problem with sObject records, such as trying to access a eld which is
not available.
The sObject exception can be caught in the catch block using an argument of the ‘SObjectException’ built-in
exception type.
For example, if the code attempts to assign a variable to a eld that has not been retrieved in the SOQL query, an
SObjectException is thrown.

SObjectException Example

Privacy - Terms

Execution Log
https://focusonforce.com/lessons/logic-and-process-automation-ii/ 10/26
4/5/2020 Logic and Process Automation II – focusonforce.com
g
TAKE NOTES

Limit Exceptions

A LimitException occurs when a governor limit has been exceeded.

This type of exception cannot be caught.

When there are too many DML statements in code, it results in an error message that says “System.LimitException:
Too Many DML statements: 151.”
When there are too many SOQL queries in code, it results in an error message that says “System.LimitException: Too
many SOQL queries: 101.”
When there are too many SOSL queries in code, it results in an error message that says “System.LimitException: Too
many SOSL queries: 21.”
If a namespace has been de ned, it is included in the error message.

Too Many DML Statements in Code

Execute Anonymous Error

Too Many SOQL Queries in Code

Execute Anonymous Error

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 11/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

Too Many SOSL Queries in Code

Execute Anonymous Error

Exception Methods

Exception methods can be used to obtain information about an exception.

The getMessage method returns the error message associated with the exception.

The getCause method returns the cause of the exception.

The getLineNumber method returns the line number where the exception was thrown.

The getStackTraceString method returns the stack trace as a string.

The getTypeName method returns the type of exception, such as DmlException and ListException.

Some speci c methods apply to DmlException only:

GetDmlFieldNames returns the names of elds that caused the error.


GetDmlId returns the ID of the failed record that caused the error.
GetDmlMessage returns the error message for the failed record.
GetNumDml returns the number of failed records.

Using Multiple Exception Types

Multiple catch blocks can be used for each exception type in order to catch different types of exceptions.

The generic Exception type can also be used to catch all exception types.

Only one catch block is executed and the remaining ones are bypassed.
The generic Exception type can be used with other built-in exception types.

Using the generic Exception type in the last catch block is useful for catching any exception that is not caught in the
previous catch blocks.

Example of Using Multiple Exception Types

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 12/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

Execution Log

Custom Exceptions

Custom exceptions can be created to throw and catch them in Apex. Built-in exceptions can only be caught.

Detailed error message and custom error handling can be speci ed using custom exceptions.
A custom exception class is created by extending the built-in ‘Exception’ class and making sure that the

class name ends with the word ‘Exception’.


All common Exception methods are inherited by a custom exception class.

The ‘throw’ keyword is used to throw the custom exception in code.

Privacy - Terms

Example of Custom Exception Creation


https://focusonforce.com/lessons/logic-and-process-automation-ii/ 13/26
4/5/2020 Logic and Process Automation II – focusonforce.com
Example of Custom Exception Creation
TAKE NOTES

Execution Log

Visualforce Exceptions

Exceptions in a custom controller or controller extension for a Visualforce page can be handled.

The ApexPages.Message class can be used to create a message for display.

The error message can be displayed by including the Message component on the page.

Bulk DML Exceptions

Errors that occur due to a bulk DML call are handled according to the origin of the call.

If the bulk DML call originates from Apex DML statements, all records must be updated successfully without an
error or the entire operation is rolled back.
If the bulk DML call originates from the SOAP API with default settings, then the runtime engine attempts at
least a partial save if there is an error.
Database class methods can be used to allow partial success of a bulk DML operation if errors are
encountered.
If the ‘allOrNone’ parameter of a Database DML method is speci ed as true, all records must be updated

successfully without an error or the entire operation is rolled back.


If the ‘allOrNone’ parameter of a Database DML method is speci ed as false, then the runtime engine attempts at

least a partial save if there is an error.


A result object or a result object array can be used to return the status of each operation and any errors
encountered.

Bulk Trigger on the Case Object

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 14/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

Mixed DML Errors

DML operations on setup objects cannot be mixed with DML operations on other sObjects in the same
transaction.
This is because some sObjects affect the user’s access to records in the org.

A mixed DML error occurs if a user tries mixed DML operations.


For instance, an account and user pro le cannot be updated in the same transaction.
Other examples of setup objects that cannot be used with other sObjects are FieldPermissions, ObjectPermissions,
 PermissionSet, Territory2, QueueSObject, etc.

Mixed DML Error Example

Execute Anonymous Error

Mixed DML Error Example

Execute Anonymous Error

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 15/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

Transactional Intergrity

An Apex transaction completes successfully when all the Apex code has nished running.
If a request by a trigger, class method, Web Service, Visualforce page or anonymous block does not complete successfully
due to an exception, all database changes are rolled back.

Only if the entire transaction completes successfully, all changes are committed to the database.
A savepoint variable can be generated to roll back partial code so that processing can continue in another
direction.
The database can be restored to the same condition it was in at the time the savepoint variable was generated, and
any DML statements after the savepoint can be discarded.
The setSavepoint and rollback Database methods can be used to generate a savepoint and perform a rollback
operation.

Considerations for Transaction Control

If more than one savepoint is set, and a user rolls back to a savepoint that is not the last savepoint, the later savepoint
variables become invalid.
Each savepoint and rollback counts against the governor limit for DML statements.
The ID on an sObject inserted after setting a savepoint is not cleared after a rollback.

Example of Two Savepoint Variables

Execute Anonymous Error

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 16/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

Learn More

Exceptions in Apex 
Apex Transactions 
sObjects That Cannot Be Used Together in DML Operations
Error: System.LimitException: Too many SOQL queries: 101
Transaction Control

Identify the keywords used in a SOQL query and explain where they're used in a query's structure

After studying this topic, you should be able to:

Identify what a SOQL query is and where it can be used

Describe the keywords that can be used in a SOQL query

Describe how the keywords are used in a SOQL query

Introduction

The Salesforce Object Query Language (SOQL) is used for querying records in a Salesforce org database. SOQL can be used when the
location (object) of the data is known.

SOQL queries can be executed in the following environments:


The queryString parameter of the Database.query() method
Apex code
Visualforce controllers and getter methods
Salesforce CLI
Visual Studio Code with the Salesforce extension pack and Salesforce CLI

SOQL keywords are reserved words that are used in a SOQL statement to de ne the objective of the query and speci cations of the
returned results. The following section describes those keywords and how to use them.

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 17/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

SOQL SELECT

The SELECT command is used to select elds that need to be returned, and the FROM command is used to specify which
object to query. The following are important considerations for using SELECT:

Only elds included in the SELECT clause are returned, except for the ID eld which is always returned even if not speci ed
in the query.

The eld list in a SELECT clause can contain:


Direct elds or related elds, e.g. SELECT eld1, parent. eld2
Aggregate functions, e.g., SELECT COUNT( eld1), MAX( eld2)
A Subquery (a nested SELECT statement)

Polymorphic relationship elds (using the TYPEOF clause)

The following aggregate functions are supported:


AVG() - returns the average value of a speci ed numeric eld
COUNT() and COUNT( eldName) - counts the number of records that matched the query criteria
COUNT_DISTINCT() - returns the number of unique/distinct non-null eld values in a query result
MIN() - returns the minimum value of a speci ed eld in a query result
MAX() - returns the maximum value of a speci ed eld in a query result
SUM() - returns the total sum of a speci ed numeric eld in a query result

Bindings to Apex variables or expressions are supported.


Example format: SELECT one or more elds FROM an object
Example query: SELECT Id, Name FROM Account

SOQL WHERE

The WHERE clause can be used in a query to specify a condition expression that includes one or more eld expressions. Only
records that meet the condition expression in the clause are returned.

The following are important considerations for using WHERE:


Logical operators can be used to add multiple eld expressions to a condition.
Parentheses can be used to de ne the order in which eld expressions are evaluated.
Example format: SELECT one or more elds FROM an object WHERE condition expression
Example query: SELECT Id, Name FROM Account WHERE (Type = 'Member' AND AccountSource = 'Partner Referral') OR
Rating = 'Hot'

SOQL Operators

SOQL operators are used in the eld expression syntax of a WHERE clause for comparison and arithmetic operations. They
specify conditions in the clause and also serve as conjunctions to allow multiple eld expressions in a condition.

Comparison Operators

=, !=, <, >, <=, and >= - These are operators used for equals, not equals, less than, less or equal, greater than, and
greater or equal comparison respectively.
LIKE - An expression is true if the eld value matches the speci ed text string. Partial text string matching and wildcards
are supported, e.g., “WHERE Name LIKE 'Focus%'” will return records which names start with "Focus".
IN - An expression is true if the eld value equals any of the speci ed values, e.g., WHERE Interests IN ('Music', 'Sports',
'Arts').
NOT IN - An expression is true if the eld value does not equal any of the speci ed values, e.g., WHERE Status NOT IN
('Suspended', 'Inactive').
INCLUDES - An expression is true if the multi-select picklist eld value meets the speci ed selections, e.g., WHERE Color
includes ('Red;Blue','Green').
EXCLUDES - An expression is true if the multi-select picklist eld value does not meet the speci ed selections, e.g., Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 18/26
4/5/2020 Logic and Process Automation II – focusonforce.com
WHERE Animal excludes('Dog;Cat','Chicken;Duck').
TAKE NOTES

Logical Operators

AND - A result is true if both expression A and expression B are true.


OR - A result is true if either expression A or expression B is true.
NOT - A result is true if an expression is false.

SOQL Wildcards

The % and _ wildcards are supported for the LIKE operator.


The % wildcard matches zero or more characters.
The _ wildcard matches exactly one character.
Example: SELECT Id, LastName FROM Contact WHERE LastName LIKE ‘Ab%’

SOQL Wildcards

SOQL Date Literals

A date literal in SOQL is an expression that represents a relative range of time, such as yesterday, tomorrow, 5 weeks from now,
or 3 quarters from today.

Some date literals are listed below:


YESTERDAY - date range starts at 00:00:00 on the day before up to 24 hours e.g. WHERE CreatedDate = YESTERDAY
NEXT_WEEK - date range starts at 00:00:00 on the rst day of the next week up to 7 full days e.g. WHERE Birthdate =
NEXT_WEEK
LAST_90_DAYS - date range starts at 00:00:00 of the current day and goes back 90 full days e.g. WHERE CloseDate >
LAST_90_DAYS
Privacy - Terms

NEXT_N_MONTHS:n - date range starts at 00:00:00 of the rst day of the next month up to the number of months
https://focusonforce.com/lessons/logic-and-process-automation-ii/ 19/26
4/5/2020 Logic and Process Automation II – focusonforce.com

speci ed by "n" e.g. WHERE TargetDate__c > NEXT_N_MONTHS:6 TAKE NOTES

SOQL ORDER BY

The ORDER BY clause can be used to control the order of the query results and can be sorted in ascending or descending order.

The following are important considerations for using ORDER BY:


The default order of a query result is ascending (ASC). To sort in descending order, DESC is used.

Null records can be ordered at the beginning (NULLS FIRST) or end (NULLS LAST) of the query results.
Fields in a related record can be used as ORDER BY elds.
Results can be sorted by multiple columns by separating each eld expression with a comma.
Multi-select picklist, rich text area, long text area, encrypted, and data category group reference cannot be used in ORDER
BY elds.
Example format: SELECT one or more elds FROM an object ORDER BY sorting condition
Example query: SELECT Id, Name FROM Account ORDER BY Name ASC NULLS FIRST

SOQL LIMIT

The LIMIT clause can be used to specify the maximum number of records to return.

The following should be noted for using LIMIT:


The LIMIT clause cannot be used in a query that uses aggregate functions but does not use a GROUP BY clause. For
example:
This query will fail: SELECT StageName, Count(Id) FROM Opportunity LIMIT 10. 
This query will succeed: SELECT StageName, Count(Id) FROM Opportunity GROUP BY StageName LIMIT 10.
Example format: SELECT one or more elds FROM an object WHERE condition expression LIMIT number of rows
Example query: SELECT Name, Email FROM Contact WHERE Email != ‘’ LIMIT 100

SOQL OFFSET

The OFFSET clause can be used to specify a starting row offset into the result set returned by the query. The offset calculation
takes place in the server, and only the result subset is returned. So, in a result of 100 records, for example, only the records after
the 20th record can be chosen to be returned by specifying OFFSET 21 in the query. This will result to returning a total of 80
records only.

The following are important considerations for using OFFSET:


The maximum offset value is 2,000 rows. When exceeded, an exception will occur.
The OFFSET clause cannot be used in a subquery unless the parent query speci cally has a LIMIT 1 clause. Otherwise, an
exception will occur.
When using OFFSET to retrieve subsets from the same result set, as in pagination, it should be used together with the
ORDER BY and LIMIT clauses.
Example format: SELECT one or more elds FROM an object ORDER BY sorting condition LIMIT number of rows

OFFSET start at
Example query: SELECT Owner.Name, Message FROM Comment__c ORDER BY CreatedDate DESC LIMIT 50 OFFSET
150
The example query will result to returning records 51 to 100 provided that they exist.

Example Usage of the Keywords in a SOQL Query

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 20/26
4/5/2020 Logic and Process Automation II – focusonforce.com

TAKE NOTES

SOQL WITH

The WITH clause can be used to lter records based on eld values. However, this clause can only be used in the following cases:
For ltering records based on categorization (WITH DATA CATEGORY)
For querying and retrieving record changes tracked in a user pro le feed (Custom Object__Feed)
For ltering records based on user access permissions on elds or objects (WITH SECURITY_ENFORCED). This is,
however, a BETA feature.

The following are important to consider when using WITH:


Unlike the WHERE clause, the WITH clause does not only support elds from the object speci ed in the FROM clause.
If WITH is speci ed, the query only returns records that match the lter and are visible to the user.
Example format: SELECT one or more elds FROM an object WHERE condition expression WITH lter statements
Example query: SELECT Title FROM KnowledgeArticleVersion WHERE PublishStatus='online' WITH DATA CATEGORY
Product__c AT Desktop__c
The example query will lter Knowledge articles based on one or more data category groups.

SOQL GROUP BY

The GROUP BY clause can be used to specify records by group and avoid the need to iterate through individual records in the
returned results to aggregate data.

Note the following for GROUP BY:

A GROUP BY clause can be used on a SELECT clause with aggregate functions, such as COUNT, SUM, MAX, etc.
If the list of elds in the SELECT clause includes an aggregate function, all non-aggregated elds must be included in the
GROUP BY clause. For example:
 This query will fail: SELECT LeadSource, Status, COUNT(Id) FROM Lead GROUP BY LeadSource.
But, this query will succeed: SELECT LeadSource, Status, COUNT(Id) FROM Lead GROUP BY LeadSource, Status
Although the GROUP BY clause is typically used on a query with aggregate elds, it can also be used on a query that do not
use an aggregate function.
The COUNT_DISTINCT() function can be used to return the number of distinct non-null values matching the criteria in the
query.
Example format: SELECT one or more elds, aggregate eld FROM an object GROUP BY non-aggregate eld
Example query: SELECT LeadSource, COUNT(Name) FROM Lead GROUP BY LeadSource

Below are two more clauses and a function related to grouping in SOQL queries:

GROUP BY ROLLUP
When GROUP BY ROLLUP is used in a query, subtotals are added (as the last row) for aggregated data in the query
results.
More than one eld can be rolled up, e.g., GROUP BY ROLLUP(StageName, Amount).
GROUP BY and GROUP BY ROLLUP cannot be used together in the same SOQL statement.

GROUP BY CUBE
When GROUP BY CUBE is used in a query, subtotals for all combinations of grouped elds are added in the query
results.
Up to three elds can be included in a GROUP by clause, e.g., GROUP BY CUBE(Type, MailingCountry, BillingCountry).
GROUP BY and GROUP BY CUBE cannot be used together in the same SOQL statement.

GROUPING
GROUPING ( eldname) can be used to determine whether a row is a subtotal or a eld when GROUP BY ROLLUP or
GROUP BY CUBE is used.
GROUPING will return 1 if the row is a subtotal for the eld, and 0 otherwise.
For example, SELECT LeadSource, GROUPING(LeadSource) grpLS, COUNT(Name) cnt FROM Lead GROUP BY
ROLLUP(LeadSource)
Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 21/26
4/5/2020 Logic and Process Automation II – focusonforce.com

GROUP BY ROLLUP Example TAKE NOTES

SOQL HAVING

The HAVING clause can be used to lter the results returned by an aggregate function in a query.

The following are important things to note:


Aggregate functions such as COUNT() and SUM() can be included in the HAVING clause but not in the WHERE clause.
It can be used with the GROUP BY clause to summarize data by a certain eld.
Example format: SELECT one or more elds, aggregate eld FROM an object GROUP BY non-aggregate eld

HAVING condition expression


Example query: SELECT Name, Count(Id) FROM Account GROUP BY Name HAVING Count(Id) > 1
The example query will return accounts with duplicate names

OTHER SOQL KEYWORDS

USING SCOPE - Records within a speci ed scope are returned. The scope values are Delegated, Everything, Mine,
MineAndMyGroups, My_Territory, My_Team_Territory, Team. For example, the following query, SELECT Name, Phone,
Website FROM Account USING SCOPE Mine, will return accounts belonging to the current user.

TYPEOF - A clause that can be used in a SELECT statement which queries data that contains polymorphic relationships.
The TYPEOF expression speci es a set of elds to choose from based on the type of the polymorphic reference during run
time. The example query below returns a set of elds based on the What eld the Event object references to:
SELECT
  TYPEOF What
    WHEN Account THEN Name, Website, Phone
    WHEN Contact THEN Title, Name, Email, Phone
    WHEN Opportunity THEN Name, Amount, CloseDate
    ELSE Name, Email
  END
FROM Event

FOR VIEW - When added in a query, the LastViewedDate elds of the returned records will be updated. This results to
these records being added to the RecentlyViewedObject and shows up in the Recent Items and global search auto-
complete lists of the user. For example, SELECT Name, ID FROM Contact LIMIT 1 FOR VIEW

FOR REFERENCE - When added in a query, the LastReferencedDate elds of the returned records will be updated. This
results to these records being added to the RecentlyViewedObject and shows up in the Recent Items and global search
auto-complete lists of the user. For example, SELECT Name, ID FROM Contact LIMIT 1 FOR REFERENCE

FOR UPDATE - When added in a query, the returned records will be locked and ensures that, during a speci ed time,
only the locking client can make changes to the records. Other users will have read access to the locked record. If the
record is not unlocked within 10 seconds, a query exception will occur. For example, SELECT Id FROM Account WHERE Id Privacy - Terms

'001ABCDEFGH1234567' LIMIT 1 FOR UPDATE


https://focusonforce.com/lessons/logic-and-process-automation-ii/ 22/26
4/5/2020 Logic and Process Automation II – focusonforce.com
= '001ABCDEFGH1234567' LIMIT 1 FOR UPDATE
TAKE NOTES

ALL ROWS - When added in a query, all records in the organization will be queried including records in the Recycle bin
as well as archived activities. For example, SELECT Id, Name FROM Contact WHERE Email = 'john@smith.com' ALL ROWS

UPDATE TRACKING - Keywords used in searching Salesforce Knowledge articles can be tracked by using UPDATE
TRACKING. For example, running the query will report on article searches and views: SELECT Title FROM FAQ__kav
WHERE Keyword = 'soql' and Language = 'en_US' and KnowledgeArticleVersion = 'kaXXXXXXXXXXXXX' UPDATE
TRACKING

UPDATE VIEWSTAT - View statistics of a Salesforce Knowledge article can be updated by using the UPDATE
VIEWSTAT clause. For example, running the query will increase the view count of the article you have access to: SELECT
Title FROM FAQ__kav WHERE PublishStatus = 'online' and Language = 'en_UK' and KnowledgeArticleVersion =
'kaXXXXXXXXXXXXX' UPDATE VIEWSTAT

Learn More

Salesforce Object Query Language (SOQL)


SOQL SELECT Syntax
Aggregate Functions
Date Formats and Date Literals

Review

COMMENTS

Mathieu Des
Hi,

In the section ‘Demonstrate knowledge of the best practices for writing Apex triggers’, I am not really sure about the ef cient apex
trigger, what are you gonna do in your HelperClass.helperMethodForWonOpportunities(o) and
HelperClass.helperMethodForLostOpportunities(o)? If you update your Opportunities inside, that won’t be good because you’re in a
for loop.
I would do something like that in my trigger:

//———————————————————————
List listWonOpportunities = new List();
List listLostOpportunities = new List();
for(Opportunity o : wonAndLostOpportunities){
if(o.StageName = ‘Closed Won’){
listWonOpportunities.add(o);
}
else if (o.StageName = ‘Closed Lost’){
listLostOpportunities.add(o);
}
}
if(!listWonOpportunities.isEmpty()){
HelperClass.helperMethodForWonOpportunities(listWonOpportunities);
}
if(!listLostOpportunities.isEmpty()){
HelperClass.helperMethodForLostOpportunities(listLostOpportunities);
Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 23/26
4/5/2020 Logic and Process Automation II – focusonforce.com
}
TAKE NOTES
//———————————————————————

Please correct me if I’m wrong.

Thanks,

1 week ago

Ian
Hi Mathieu, thank you for pointing this out. That is correct, DML statements should be operated on bulk records whenever
possible as best practice. We’ll update the code snippet.

7 days ago

Max
Great content! I love the Exception section explanation.

6 months ago

Ian
Thanks, Maxim!

5 months ago

ryanshout
The Apex Trigger Best Practices section is here! It looks great! Thanks FocusOnForce!

6 months ago

Zrna
Hi Ryan, thanks for the nice words about our content, and thanks for being patient and waiting for new updates. All PD2
updates are done, so all users can be sure that content is up to date with the latest release.

6 months ago

Gian Marco Elera Garay


Salesforce has incresead the maximun size of Debug Logs from 5mb to 20 mb, Also the debug logs we can generate in a 15 minutes
window

9 months ago

Gian Marco Elera Garay


Also the debug logs we can generate in a 15 minutes window is increased to 1000 mb

9 months ago

Zrna
Thanks for letting us know, we will update that info as well.

9 months ago

Zrna
Privacy - Terms
Thanks for noticing that and letting us know. We will update the lessons.
https://focusonforce.com/lessons/logic-and-process-automation-ii/ 24/26
4/5/2020 Logic and Process Automation II – focusonforce.com
9 months ago
TAKE NOTES

Arnold
In the screenshot for “Simplify logic by using one trigger per object, helper methods and less statements”, you have forgotten to
externalise the contact SOQL query out of the for loop. You have a for loop for accounts, which executes the contact SOQL query for
each account. As stated in your point above, SOQL statements should not be in loops. I would create a map of accounts, then just
have one for loop for the contacts SOQL, then in the contact for loop I can get the associated account from the account map by:
accountsMap.get(con.AccountId).Type

9 months ago

AP
Thanks for your feedback. The Contact SOQL query is not ‘inside’ the FOR loop here; it is in the de nition of the loop.

9 months ago

Alexander
Maybe you could explain the difference between governor limits (Limits class) and API limits (OrgLimits class). OrgLimits class was
introduced in v45.

10 months ago

AP
Thanks for the feedback. We will add a new section that explains the OrgLimits class to the following topic: “Logic and
Process Automation 6: Identify potential issues with inef cient code and mitigation techniques to avoid exceeding
governor limits”

9 months ago

Matt Edmondson
The number of @future invocations in a single Apex transaction is now 50, not 10. https://developer.salesforce.com/docs/atlas.en-
us.apexcode.meta/apexcode/apex_gov_limits.htm

1 year ago

Sara S.
The limit of 10 @future calls is still applicable, as one can see in the ‘Miscellaneous Apex Limits’ section on the page below.
The limit of 50 is for synchronous Apex transactions and refers to the maximum number of methods with @future
annotation that are allowed.

“If your triggers call future methods, they are subject to a limit of 10 future calls per batch.”

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm

1 year ago

Nick Zozaya
The “Governors in Apex Code” link in the ‘Learn More’ sub-section of the last section is broken.

1 year ago

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 25/26
4/5/2020 Logic and Process Automation II – focusonforce.com
Sara S. TAKE NOTES
Hi Nick, thank you for your feedback. The link has been replaced.

1 year ago

ttms.akademiaSFDC
Debug logs can now reach up to 5MB.

1 year ago

Sara S.
Hi, thank you for your feedback. The content has been updated.

1 year ago

Bupali
Stake Tree – In the Salesforce document in here says top-down view, but it seems to me it is bottom-up view. Can somebody con rm?

1 year ago

Sara S.
Hi Bupali,

The ‘top-down’ view means that it shows the method calls starting from the initiating call to the next level down. The
Salesforce help page below also explains this.

https://help.salesforce.com/articleView?id=code_dev_console_view_system_log.htm&type=5

1 year ago

Your Comment...

Comment

Copyright 2020 - www.focusonforce.com

About Blog Contact Us Disclaimer Privacy Policy Terms of Use View as Mobile

Privacy - Terms

https://focusonforce.com/lessons/logic-and-process-automation-ii/ 26/26

You might also like