SOQL Query in Salesforce Apex & Examples
SOQL Query in Salesforce Apex & Examples
Table of Contents
What is SOQL?
SOQL Cheat Sheet
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 1 of 44
:
Aggregate Functions
FAQs
SOQL stands for Salesforce Object Query Language. SOQL can be used to access
information stored in your organization’s database. The syntax of SOQL is similar to
that of SQL (Structured Query Language).SOQL queries can be written in Apex code
or in the Query Editor of the Developer Console. In Soql records can only be
searched on a single sObject if it meets the given criteria. Unlike SOSL, it cannot
search across multiple objects but nested queries are supported in SOQL.
Code Example:
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 2 of 44
:
!" Create a list to store the queried invoice records
List<apex_invoice!#c> invoiceList = new List<apex_invoice!#c>();
try {
!" Querying the invoice records with specific criteria
!" Selecting fields Id, Name, APEX_Customer!#r.Name, APEX_Status!#c
!" from the APEX_Invoice!#c object where the record was created today
!" and the customer name is not 'Test'
invoiceList = [SELECT Id, Name, APEX_Customer!#r.Name, APEX_Status!#c
FROM APEX_Invoice!#c
WHERE CreatedDate = TODAY AND APEX_Customer!#r.Name !$ 'Test'];
!" Looping through each fetched record and printing its values
for (apex_invoice!#c objInvoice : invoiceList) {
!" Printing the record's values
System.debug('Record value: ' + objInvoice);
}
} catch (Exception e) {
!" Handling any exceptions that might occur during the query execution
System.debug('An error occurred: ' + e.getMessage());
}
Explanation:
1. Fetching Records via SOQL: We’re using a Salesforce Object Query Language
(SOQL) query to retrieve records from the APEX_Invoice__c object.
2. Query Criteria: We’re querying records created today ( CreatedDate =
TODAY ) and whose customer name is not ‘Test’ ( APEX_Customer__r.Name
!= 'Test' ).
3. Error Handling: We’ve added a try-catch block to catch any exceptions that
might occur during the query execution.
4. Printing Records: We’re printing the total number of fetched records and
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 3 of 44
:
looping through each record to print its values using System.debug() . This
helps in debugging and understanding the data retrieved from the query.
SQL (Structured Query Language) is the standard language for managing and
manipulating databases. Here’s an overview of the basic syntax used in SQL to
perform common operations such as selecting data, inserting records, updating
records, and deleting records.
1. SELECT Statement
The SELECT statement is used to select data from a database. Data is retrieved
from one or more tables.
Syntax:
The INSERT INTO statement is used to insert new records into a table.
Syntax:
3. UPDATE Statement
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 4 of 44
:
The UPDATE statement is used to modify the existing records in a table.
Syntax:
UPDATE tableName
SET column1 = value1, column2 = value2, !!%
WHERE condition;
4. DELETE Statement
Syntax:
The CREATE TABLE statement is used to create a new table in the database.
Syntax:
Additional Clauses
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 5 of 44
:
WHERE: Specifies conditions for the SELECT , UPDATE , and DELETE
statements.
GROUP BY: Groups rows that have the same values in specified columns into
summary rows.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 6 of 44
:
of rows returned.
ORDER BY Specifies the order SELECT Name FROM Account ORDER BY Name
of returned rows. ASC
This cheat sheet covers the basic syntax and common uses of SOQL commands to
help with quick reference during development.
Example:
In this example, :name is a bind variable that gets replaced with the value of the
name variable when the query is executed. This approach helps protect against
SOQL injection and allows for more flexible query construction.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 8 of 44
:
FROM: Specifies the object from which to retrieve records.
ORDER BY: Specifies the sorting order for the query results.
SELECT Industry, COUNT(Id) FROM Account GROUP BY Industry HAVING COUNT(Id) > 1
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 9 of 44
:
SELECT Id, Name FROM Account LIMIT 10
SELECT Id, Name FROM Account WHERE Industry NOT IN ('Retail', 'Healthcare')
SELECT Id, Name FROM Account WHERE Industry = 'Technology' AND AnnualRevenue > 10000
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 10 of 44
:
SELECT Id, Name FROM Account WHERE Industry = 'Technology' OR Industry = 'Finance'
SELECT Id, Name FROM Account WHERE Name = 'Acme' FOR UPDATE
ALL ROWS: Allows querying of all records, including archived and deleted records
SELECT Id, Name FROM Account WHERE Name = 'Acme' ALL ROWS
!" Using Account!#r.Industry to access the Industry field of the related Account
String accountIndustry = contact.Account!#r.Industry;
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 11 of 44
:
!" Printing contact and related Account information
System.debug('Contact Name: ' + contactName);
System.debug('Contact Email: ' + contactEmail);
System.debug('Related Account Name: ' + accountName);
System.debug('Related Account Industry: ' + accountIndustry);
}
Explanation:
1. SOQL Query: We are querying Contact records along with their related
3. Accessing Fields: Within the loop, we access fields of both the Contact and
.
4. Debugging: We print out information about each Contact and its related
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 12 of 44
:
!" Define the ID of the parent Account record
Id parentAccountId = 'Insert_Account_ID_Here'; !" Replace with actual Account ID
Explanation:
1. Parent Account ID: We define the ID of the parent Account record from which
4. Accessing Fields: Within the loop, we access fields of each child Contact
using dot notation ( . ). For example, childContact.Name accesses the Name
field of the child Contact .
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 13 of 44
:
5. Debugging: We print out information about each child Contact using
System.debug() statements for debugging purposes.
!" Querying the parent Account record related to the child Contact
Contact childContact = [SELECT Id, Name, Email, AccountId, Account.Name, Account.Ind
FROM Contact
WHERE Id = :childContactId];
!" Accessing parent Account fields from the related Contact record
String accountId = childContact.AccountId;
String accountName = childContact.Account.Name;
String accountIndustry = childContact.Account.Industry;
Explanation:
1. Child Contact ID: We define the ID of the child Contact record for which we
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 14 of 44
:
'Insert_Contact_ID_Here' with the actual ID of the child Contact .
2. SOQL Query: We use a SOQL query to retrieve the child Contact record along
with the related parent Account information ( SELECT Id, Name, Email,
You can explore all the String methods in Apex, and learn those examples for each
method.
Explanation:
method.
4. Printing: We print out the stage name, total amount, and average amount for
each stage using System.debug() statements.
Watch our FREE Salesforce online course video, it’s a full length free tutorial for
beginners.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 16 of 44
:
Binding Apex Variables in SOQL
Binding Apex variables, also known as binding variables or bind expressions, are
used to dynamically pass values into SOQL queries, SOSL searches, and dynamic
SOQL queries in Salesforce. They help prevent SOQL injection and improve
performance. Here are examples of how to use binding variables in various contexts:
String soqlQuery = 'SELECT Id, Name, Email FROM ' + objectType + ' WHERE ' + fieldNa
List<SObject> records = Database.query(soqlQuery);
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 17 of 44
:
Read more: Workflow rules in Salesforce
Here, searchKey is bound to the SOSL search query using the :searchKey
syntax. This searches for the specified keyword in all fields of the Contact object.
Binding variables help make queries and DML operations dynamic, secure, and
efficient by allowing values to be passed dynamically into queries and DML
statements, thus preventing SOQL injection attacks and improving performance.
Step 1: Open the developer console and click on the Debug tab to open the
anonymous window as shown below the image.
Using the Query Editor, we can now write and execute a SOQL query to fetch the
above-inserted records. A SOQL query searches for data in a specific object and
optionally, you may add a condition to the WHERE clause to filter your search.
In the image below we have queried the Account and its associated contact and
opportunity records and filtered the result by Account Name.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 19 of 44
:
Key Features:
1. SOQL allows you to query records from Standard and Custom objects in one go.
2. SOQL allows querying on a single object or multiple objects that are related to
one another.
3. SOQL supports aggregate functions just like SQL. We can roll up and
summarize data with aggregate functions. For example, Avg, Min, Max, etc.
4. SOQl allows binding apex variables in the query to filter the records.
Watch our FREE Salesforce online course video, it’s a full length free tutorial for
beginners.
SOSL, or Salesforce Object Search Language, is like a powerful tool I use to find
stuff in Salesforce. Imagine I’m searching for a specific word in a big library full of
books. SOSL helps me do just that. It’s like a magic spell that lets me search across
multiple books, not just one, to find what I need. So, instead of looking through each
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 20 of 44
:
book one by one, SOSL quickly sifts through all the books and shows me the ones
that mention the word I’m looking for. It’s super handy when I need to find
information fast and don’t want to spend all day searching.
SOQL and SOSL are like cousins to SQL, but not identical twins. They speak a
similar language, but they have their own quirks tailored specifically for Salesforce.
Imagine SQL as the language you use to talk to a big library full of books, while
SOQL and SOSL are the languages you use to talk to a specialized library, like a
library of comic books or recipe books. They understand each other to some extent,
but they also have their own unique words and phrases that make them different.
So, while you might recognize some similarities between them, they’re not exactly
the same, just like cousins who share a family resemblance but have their own
distinct personalities. SOQL and SOSL are designed for querying data within the
Salesforce platform, each serving a specific purpose: SOQL for querying records
from Salesforce objects and SOSL for performing full-text searches across multiple
objects.
Examples:
SOQL Query:
This SOQL query retrieves the Id, Name, and the related Account’s Name of all
contacts where the related Account’s Name is ‘ACME’.
SOSL Query:
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 21 of 44
:
FIND {ACME} IN ALL FIELDS RETURNING Contact(Id, Name), Account(Name)
This SOSL query searches for the keyword ‘ACME’ across all fields of the Contact
and Account objects and returns matching Contact records with their Id and Name,
as well as matching Account records with their Name.
SQL Query:
This SOSL query searches for the keyword ‘ACME’ across all fields of the Contact
and Account objects and returns matching Contact records with their Id and Name,
as well as matching Account records with their Name.
To write a basic SOQL (Salesforce Object Query Language) query, you can use the
SELECT statement followed by the fields you want to retrieve from a Salesforce
object. Here’s a basic example of a SOQL query:
In this example, the query retrieves the Id , Name , and AccountNumber fields from
the Account object in Salesforce.
You can execute this query using Salesforce’s JavaScript Remoting, Apex, or other
Salesforce API methods depending on your use case. For example, using
JavaScript Remoting, you would define a remote action in your Apex controller and
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 22 of 44
:
call it from your JavaScript code:
Apex Controller:
JavaScript
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.AccountController.getAccounts}',
function(result, event) {
if (event.status) {
!" Process the result
console.log(result);
} else {
console.error(event.message);
}
}
);
This is a basic example, and SOQL queries can be more complex, including
conditions ( WHERE clause), ordering ( ORDER BY ), and grouping ( GROUP BY ).
To write a basic SOQL (Salesforce Object Query Language) query, you first specify
the fields you want to retrieve using the SELECT clause. For instance, let’s say we
want to retrieve the “Name” and “Industry” fields from the “Account” object. We
would write the SELECT clause like this: “SELECT Name, Industry”. This tells
Salesforce to return the “Name” and “Industry” fields in the query results.
Next, we specify the object from which we want to retrieve the data using the FROM
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 23 of 44
:
clause. In this example, we want to retrieve data from the “Account” object, so we
write “FROM Account”. This indicates that we want to query data from the “Account”
object specifically.
Putting it all together, our basic SOQL query looks like this: “SELECT Name,
Industry FROM Account”. This query tells Salesforce to retrieve the “Name” and
“Industry” fields from the “Account” object. It’s a simple yet powerful way to extract
specific information from Salesforce objects, and it forms the foundation for more
complex queries involving additional clauses like WHERE, ORDER BY, GROUP BY,
and others.
To find Object and Field API Names for your queries in Salesforce, you can utilize
several methods. One common approach is to navigate to the Object Manager
within the Salesforce Setup menu. From there, you can search for the specific object
you’re interested in, such as “Account” or “Contact.” Once you locate the object, click
on it to access its details. Here, you’ll find a list of all the fields associated with that
object, along with their respective API Names. These API Names serve as unique
identifiers for each field and are crucial for referencing them accurately in your SOQL
queries.
By leveraging these methods, you can efficiently discover Object and Field API
Names required for your SOQL queries in Salesforce. Whether you’re a Salesforce
administrator, developer, or consultant, understanding how to find and utilize Object
and Field API Names is essential for effectively querying and manipulating data
within the Salesforce platform.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 24 of 44
:
Using Developer Console:
Click on “Execute” to run the code. The Developer Console will display the Field
Label and API Name for each field of the Account object.
To find the Object and Field API Names for your queries in Salesforce, you can use
the Schema class in Apex. Here’s a code snippet that demonstrates how to retrieve
the API Names of an object and its fields:
!" Specify the object API name for which you want to retrieve the schema
String objectApiName = 'Account';
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 25 of 44
:
for (Schema.SObjectField field : describeResult.fields.getMap().values()) {
fieldApiNames.add(field.getDescribe().getName());
}
System.debug('Field API Names: ' + fieldApiNames);
This code snippet demonstrates how to retrieve the API Name of an object (
Account in this case) and its fields. You can modify the objectApiName variable
to specify the object for which you want to retrieve the schema.
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Industry = 'Technology'
In addition to static queries, you can construct SOQL queries dynamically at runtime
using string concatenation or by leveraging the Database.query() method. This
approach allows you to build queries based on dynamic criteria. For instance, you
might define query conditions based on user input or runtime variables. Dynamic
queries enable greater flexibility in querying data from Salesforce objects within your
Apex code. Here’s an example of constructing a dynamic SOQL query:
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 26 of 44
:
String industry = 'Technology';
String soqlQuery = 'SELECT Id, Name FROM Account WHERE Industry = \'' + industry + '
List<Account> accounts = Database.query(soqlQuery);
Furthermore, SOQL supports the use of binding variables, which allow you to
dynamically pass values into the query at runtime. Binding variables are denoted by
a colon followed by the variable name. This helps prevent SOQL injection and
enhances query security. Here’s how you can use binding variables in a SOQL
query:
Moreover, SOQL allows you to query fields on related objects using relationship
fields. For example, you can query fields on child objects using parent-child
relationship fields. Once you have executed a SOQL query, you can iterate through
the query results using standard Apex iteration methods like for loops. This enables
you to process and manipulate the retrieved data as needed within your Apex code.
By leveraging SOQL in Apex, you can effectively interact with Salesforce data and
build robust applications on the Salesforce platform.
SOQL (Salesforce Object Query Language) SOSL (Salesforce Object Search Language)
Used for querying data from specific Used for performing text searches in records
objects and their related objects. across multiple objects.
Returns records that meet specific criteria Returns records containing the search term,
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 27 of 44
:
defined in the WHERE clause. potentially from multiple object types
simultaneously.
Query targets a specific object or a specific Searches the global index of all records that
set of objects defined in the FROM clause. meet the search criteria across multiple objects.
Supports nested queries and relationship Limited to simple search conditions; does not
queries. allow nested queries or relationship queries.
Ideal for precise, complex queries where Ideal for broad, text-based searches where the
you know the structure of the database. exact location of data is unknown.
Can include COUNT, SUM, MAX, MIN, Primarily focuses on finding text in record fields
and other functions. without aggregate functions.
Has a row limit based on context, usually Has a different limit, typically 2,000 records for
50,000 records in batch Apex. global search across objects.
For those looking for Salesforce learning, CRS Info Solutions provides an
extensive Salesforce training program designed to enhance your skills and career
opportunities. Explore our Salesforce training in India to gain practical, hands-on
experience. Our training covers all essential aspects of Salesforce, ensuring
comprehensive learning. With expert instructors and a detailed curriculum, CRS
Info Solutions is committed to your success in the Salesforce ecosystem with
our Career Building program. Whether you are a beginner or looking to advance
your skills, they offer the guidance and resources you need. Enroll for free demo
today!
This example demonstrates how to retrieve account details for a specific customer
using their account ID.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 28 of 44
:
Account account = [SELECT Id, Name, BillingAddress, Phone, Industry, AnnualR
FROM Account
WHERE Id = :accountId];
return account;
}
}
This example fetches all transactions associated with a specific account within a
date range.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 29 of 44
:
Read more: Objects – Salesforce Apex
This example identifies high-value customers based on their total assets managed
by the bank.
This example retrieves all loan applications that are pending approval.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 30 of 44
:
ORDER BY Application_Date!#c DESC]
return pendingLoans;
}
}
This example demonstrates how to retrieve medical records for a specific patient
using their patient ID.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 31 of 44
:
Example 2: Fetching Appointments for a Specific Doctor
This example fetches all appointments scheduled for a specific doctor within a
specified date range.
This example demonstrates how to retrieve details for a specific flight using its flight
number.
This example fetches all reservations made by a specific passenger using their
passenger ID.
This example demonstrates how to retrieve details for a specific shipment using its
shipment ID.
This example fetches all deliveries assigned to a specific driver within a specified
date range.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 34 of 44
:
}
}
This example demonstrates how to retrieve enrollment details for a specific student
using their student ID.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 35 of 44
:
student reference, course reference, enrollment date, and status.
This example fetches all courses offered by a specific department using the
department ID.
To run SOQL queries in Salesforce, you can use several tools, including the
Salesforce Developer Console, Workbench, and the Query Editor in Salesforce
Setup. The Developer Console is a robust tool that provides a user-friendly interface
for writing and executing SOQL queries. Workbench is another powerful web-based
tool that allows you to run SOQL queries and interact with Salesforce data.
Additionally, the Query Editor, accessible through the Salesforce Setup, offers a
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 36 of 44
:
simple interface for executing SOQL queries directly within your Salesforce org.
The full form of SOQL is Salesforce Object Query Language. It is a query language
provided by Salesforce to retrieve data from the Salesforce database. SOQL is
similar to SQL (Structured Query Language) but is specifically designed to work with
Salesforce objects and fields.
1. List<sObject>: A list of standard or custom objects, where each item in the list is
performing aggregate queries such as COUNT, SUM, AVG, MIN, and MAX.
3. Integer: An integer value, usually returned when using aggregate functions like
COUNT to determine the number of records that match the query criteria.
The maximum length of a SOQL query is 20,000 characters. This limit includes the
query string and any variable bindings used in the query. It is important to be mindful
of this limit when constructing complex queries to ensure they do not exceed the
maximum allowed length.
To get a single record in SOQL, you can use the LIMIT clause to restrict the query
result to one record. For example:
This query retrieves the first account record from the Account object. It’s important to
note that if you expect only one record, you can directly assign the result to a single
sObject variable.
To fetch all records in SOQL, you write a query without any filtering criteria.
However, it’s important to be mindful of Salesforce’s governor limits. Here’s an
example:
This query retrieves all account records. If the number of records exceeds the
governor limits, you might need to use batch processing or pagination to handle the
data efficiently.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 38 of 44
:
1. Basic Queries: Simple queries that retrieve data from a single object.
// Parent-to-child
SELECT Name, (SELECT LastName FROM Contacts) FROM Account;
3. Aggregate Queries: Queries that perform aggregate functions such as COUNT,
1. Optimize Queries: Ensure your queries are efficient and retrieve only necessary
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 39 of 44
:
to process the data.
4. Use Batch Apex: For large data operations, consider using Batch Apex to
To retrieve more than 50,000 records in Salesforce SOQL, you can use one of the
following approaches:
Batch Apex: Use Batch Apex to process records in batches of up to 200 records per
batch, allowing you to handle large data sets efficiently.
Query Pagination: Use query pagination to retrieve records in smaller chunks. This
involves using the OFFSET clause or maintaining a cursor to fetch subsequent sets
of records.
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 200 OFFSET 0];
!" Repeat with different offsets to retrieve subsequent records
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 40 of 44
:
Next chapter is Security and previous chapter is SOSL Query.
← How to pass parameters to Scheduled Apex class? Mastering Single Sign-On in Salesforce →
Apex Tutorials
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 41 of 44
:
Database methods - Salesforce Apex
Name *
Name
Email address *
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 42 of 44
:
Email address
Phone *
Phone
Select Course
Salesforce
India
SEND QUERY
RECENT POSTS
TCS Java Interview Questions
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 43 of 44
:
Salesforce Admin Certification Guide Apex Tutorial Chapter 1 About us
Recent Posts
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/#soql-cheatsheet 8/21/24, 1 37 PM
Page 44 of 44
: