Write SOQL Queries Unit - Salesforce Trailhead
Write SOQL Queries Unit - Salesforce Trailhead
Search
Learning Objectives
After completing this unit, you'll be able to:
Because Apex has direct access to Salesforce records that are stored in the database, you can embed SOQL
queries in your Apex code and get results in a straightforward fashion. When SOQL is embedded in Apex, it is
referred to as inline SOQL.
To include SOQL queries within your Apex code, wrap the SOQL statement within square brackets and assign the
return value to an array of sObjects. For example, the following retrieves all account records with two fields, Name
and Phone, and returns an array of Account sObjects.
Copy
Prerequisites
Some queries in this unit expect the org to have accounts and contacts. Before you run the queries, create some
sample data.
1. In the Developer Console, open the Execute Anonymous window from the Debug menu.
2. Insert the below snippet in the window and click Execute.
Name='SFDC Computing',
Phone='(415)555-1212',
NumberOfEmployees=50,
BillingCity='San Francisco');
insert acct;
ID acctID = acct.ID;
FirstName='Carol',
LastName='Ruiz',
Phone='(415)555-1212',
https://trailhead.salesforce.com/content/learn/modules/apex_database/apex_database_soql 1/7
2/24/22, 11:48 PM Write SOQL Queries Unit | Salesforce Trailhead
Department='Wingo',
insert con;
Phone='(310)555-1213',
NumberOfEmployees=50,
BillingCity='Los Angeles',
insert acct2;
Copy
The Developer Console provides the Query Editor console, which enables you to run your SOQL queries and view
results. TheSOQL
2. Write QueryQueries
Editor provides a quick way to inspect the database. It is a good way to test your SOQL queries
before adding them to your Apex code. When you use the Query Editor, you must supply only the SOQL statement
without the Apex code that surrounds it.
Copy
All account records in your org appear in the Query Results section as rows with fields.
Copy
The WHERE clause is optional. Let’s start with a very simple query. For example, the following query retrieves
accounts and gets Name and Phone fields for each account.
Copy
1. SELECT Name,Phone : This part lists the fields that you would like to retrieve. The fields are specified after the
SELECT keyword in a comma-delimited list. Or you can specify only one field, in which case no comma is
necessary (e.g. SELECT Phone ).
2. FROM Account : This part specifies the standard or custom object that you want to retrieve. In this example,
it’s Account. For a custom object called Invoice_Statement, it is Invoice_Statement__c.
Unlike other SQL languages, you can’t specify * for all fields. You must specify every
field you want to get explicitly. If you try to access a field you haven’t specified in the
SELECT clause, you’ll get an error because the field hasn’t been retrieved.
You don’t need to specify the Id field in the query as it is always returned in Apex
queries, whether it is specified in the query or not. For example: SELECT Id,Phone FROM
https://trailhead.salesforce.com/content/learn/modules/apex_database/apex_database_soql 2/7
2/24/22, 11:48 PM Write SOQL Queries Unit | Salesforce Trailhead
Account and SELECT Phone FROM Account are equivalent statements. The only time you
1. Apex Basics & Database
may want to specify the Id field if it is the only field you’re retrieving because you
have to list at least one field: SELECT Id FROM Account . You may want to specify the Id
field also when running a query in the Query Editor as the ID field won’t be
displayed unless specified.
If you have more than one account in the org, they will all be returned. If you want to limit the accounts returned
to accounts that fulfill a certain condition, you can add this condition inside the WHERE clause. The following
example retrieves only the accounts whose names are SFDC Computing. Note that comparisons on strings are
case-insensitive.
The WHERE clause can contain multiple conditions that are grouped by using logical operators (AND, OR) and
parentheses. For example, this query returns all accounts whose name is SFDC Computing that have more than 25
employees:
Copy
This is another example with a more complex condition. This query returns all of these records:
SELECT Name,Phone FROM Account WHERE (Name='SFDC Computing' OR (NumberOfEmployees>25 AND BillingCity='Los Angeles'))
Copy
Instead of using the equal operator (=) for comparison, you can perform fuzzy
matches by using the LIKE operator. For example, you can retrieve all accounts
whose names start with SFDC by using this condition: WHERE Name LIKE 'SFDC%' . The %
wildcard character matches any or no character. The _ character in contrast can be
used to match just one character.
When a query executes, it returns records from Salesforce in no particular order, so you can’t rely on the order of
records in the returned array to be the same each time the query is run. You can however choose to sort the
returned record set by adding an ORDER BY clause and specifying the field by which the record set should be
sorted. This example sorts all retrieved accounts based on the Name field.
Copy
The default sort order is in alphabetical order, specified as ASC. The previous statement is equivalent to:
Copy
https://trailhead.salesforce.com/content/learn/modules/apex_database/apex_database_soql 3/7
2/24/22, 11:48 PM Write SOQL Queries Unit | Salesforce Trailhead
To reverse the order, use the DESC keyword for descending order:
1. Apex Basics & Database
SELECT Name,Phone FROM Account ORDER BY Name DESC
Copy
You can sort on most fields, including numeric and text fields. You can’t sort on fields like rich text and multi-select
picklists.
Try these SOQL statements in the Query Editor and see how the order of the returned record changes based on
the Name field.
You can limit the number of records returned to an arbitrary number by adding the LIMIT n clause where n is the
number of records you want returned. Limiting the result set is handy when you don’t care which records are
returned, but you just want to work with a subset of records. For example, this query retrieves the first account
that2.isWrite
returned.
SOQLNotice that the returned value is one account and not an array when using LIMIT 1 .
Queries
Copy
ORDER BY Name
LIMIT 10
Copy
Execute the following SOQL query in Apex by using the Execute Anonymous window in the Developer Console.
Then inspect the debug statements in the debug log. One sample account should be returned.
ORDER BY Name
LIMIT 10];
System.debug(accts);
Copy
SOQL statements in Apex can reference Apex code variables and expressions if they are preceded by a colon (:).
The use of a local variable within a SOQL statement is called a bind.
This example shows how to use the targetDepartment variable in the WHERE clause.
Copy
Records in Salesforce can be linked to each other through relationships: lookup relationships or master-detail
relationships. For example, the Contact has a lookup relationship to Account. When you create or update a
contact, you can associate it with an account. The contacts that are associated with the same account appear in a
https://trailhead.salesforce.com/content/learn/modules/apex_database/apex_database_soql 4/7
2/24/22, 11:48 PM Write SOQL Queries Unit | Salesforce Trailhead
related list on the account’s page. In the same way you can view related records in the Salesforce user interface,
you1.can
Apex Basics
query & Database
related records in SOQL.
To get child records related to a parent record, add an inner query for the child records. The FROM clause of the
inner query runs against the relationship name, rather than a Salesforce object name. This example contains an
inner query to get all contacts that are associated with each returned account. The FROM clause specifies the
Contacts relationship, which is a default relationship on Account that links accounts and contacts.
SELECT Name, (SELECT LastName FROM Contacts) FROM Account WHERE Name = 'SFDC Computing'
Copy
This next example embeds the example SOQL query in Apex and shows how to get the child records from the
SOQL result by using the Contacts relationship name on the sObject.
FROM Account
Copy
You can traverse a relationship from a child object (contact) to a field on its parent (Account.Name) by using dot
notation. For example, the following Apex snippet queries contact records whose first name is Carol and is able to
retrieve the name of Carol’s associated account by traversing the relationship between accounts and contacts.
Copy
Note
The examples in this section are based on standard objects. Custom objects can also be linked
together by using custom relationships. Custom relationship names end with the __r suffix. For
example, invoice statements are linked to line items through the Line_Items__r relationship on the
Invoice_Statement__c custom object.
With a SOQL for loop, you can include a SOQL query within a for loop. The results of a SOQL query can be
iterated over within the loop. SOQL for loops use a different method for retrieving records—records are retrieved
using efficient chunking with calls to the query and queryMore methods of the SOAP API. By using SOQL for
loops, you can avoid hitting the heap size limit.
SOQL for loops iterate over all of the sObject records returned by a SOQL query. The syntax of a SOQL for loop
is either:
code_block
Copy
or
code_block
}
https://trailhead.salesforce.com/content/learn/modules/apex_database/apex_database_soql 5/7
2/24/22, 11:48 PM Write SOQL Queries Unit | Salesforce Trailhead
Copy
1. Apex Basics & Database
Both variable and variable_list must be of the same type as the sObjects that are returned by the soql_query .
It is preferable to use the sObject list format of the SOQL for loop as the loop executes once for each batch of 200
sObjects. Doing so enables you to work on batches of records and perform DML operations in batch, which helps
avoid reaching governor limits.
// The sObject list format executes the for loop once per returned batch
// of records
Integer i=0;
Integer j=0;
for (Account[] tmp : [SELECT Id FROM Account WHERE Name LIKE 'for loop _']) {
j = tmp.size();
System.assertEquals(3, j); // The list should have contained the three accounts
// named 'yyy'
System.assertEquals(1, i); // Since a single batch can hold up to 200 records and,
Copy
Resources
SOQL and SOSL Reference
Get Ready
You’ll be completing this challenge in your own hands-on org. Click Launch to get started, or click the name of
your org to choose a different one.
If you use Trailhead in a language other than English, make sure that your hands-on org is set to the same
language as the challenge instructions. Otherwise you may run into issues passing this challenge. Want to find out
more about using hands-on orgs on Trailhead? Check out Trailhead Playground Management.
Your Challenge
The Apex class must be called ContactSearch and be in the public scope
The Apex class must have a public static method called searchForContacts
The method must accept two incoming strings as parameters
The method should then find any contact that has a last name matching the first string, and mailing
postal code (API name: MailingPostalCode) matching the second string
The method should finally return a list of Contact records of type List that includes the ID and Name
fields
PD1_PlattformDevelopement
Launch
Last used on 2/24/2022
Trailhead Academy Take Free Certification Prep Salesforce Developers Trailhead Store
Trailblazer Connect
https://trailhead.salesforce.com/content/learn/modules/apex_database/apex_database_soql 7/7