SOQL Query in Salesforce Apex & Examples
SOQL Query in Salesforce Apex & Examples
Reviews Contact Us
Table of Contents
What is SOQL?
SOQL Cheat Sheet
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 1/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
Hyderabad has emerged as a thriving tech city, attracting global corporations and
fostering a high demand for skilled professionals. Salesforce is one of the most
sought-after skills due to its crucial role in CRM and business management. Opting
for our job-oriented Salesforce training in Hyderabad offers a significant edge, as the
city’s robust job market is consistently growing. Leading companies like Google,
Amazon, and Microsoft are actively searching for certified Salesforce experts to
manage and optimize our Salesforce systems. Enroll for demo today!
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 2/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
try {
Reviews Contact Us
// 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'];
Explanation:
1. Fetching Records via SOQL: We’re using a Salesforce Object Query Language (SOQL)
4. Printing Records: We’re printing the total number of fetched records and looping
through each record to print its values using System.debug() . This helps in debugging
Whatsapp Chat
and understanding the data retrieved from the query.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 3/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
SQL (Structured Query Language) is the standard language for managing and manipulating
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
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.
Reviews Contact Us
Checkout: SOSL Query in Salesforce Apex
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
Syntax:
UPDATE tableName
SET column1 = value1, column2 = value2, ...
WHERE condition;
Whatsapp Chat
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 4/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
Syntax:
The CREATE TABLE statement is used to create a new table in the database.
Syntax:
Additional Clauses
WHERE: Specifies conditions for the SELECT , UPDATE , and DELETE statements.
ORDER BY: Orders the results according to one or more columns.
GROUP BY: Groups rows that have the same values in specified columns into summary
rows.
CRS Info Solutions offers a comprehensive and dynamic Salesforce online course career
Whatsapp Chat
building program for beginners, covering admin, developer, and LWC concepts. This course
features immersive real-time projects, interactive hands-on learning, detailed daily notes,
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 5/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
essential interview questions, thorough certification preparation, and strategic job prep
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
guidance. Join their inspiring free demo to embark on an exciting Salesforce journey
with expert mentorship and unlock your full potential in the Salesforce
ecosystem.
Reviews Enroll
Contactfor
Us a free demo today!
WHERE Filters results based on SELECT Name FROM Account WHERE Industry =
specified conditions. 'Finance'
LIMIT Restricts the number of rows SELECT Name FROM Account LIMIT 5
returned.
ORDER BY Specifies the order of SELECT Name FROM Account ORDER BY Name ASC
returned rows.
GROUP BY Groups results by one or SELECT Count(), Industry FROM Account GROUP
more fields. BY Industry
LIKE Filters results by pattern SELECT Name FROM Contact WHERE Email LIKE
matching. '%@example.com'
INCLUDES Used in multi-select picklists SELECT Name FROM Account WHERE Industries__c
to select values. INCLUDES ('Banking', 'Insurance')
EXCLUDES Used in multi-select picklists SELECT Name FROM Account WHERE Industries__c
to exclude values. EXCLUDES ('Retail')
TYPEOF For polymorphic SELECT TYPEOF What WHEN Account THEN Phone,
Whatsapp Chat
relationships, specifies NumberOfEmployees WHEN Opportunity THEN
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 6/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
Reviews
SOQL Cheat SheetContact Us
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.
and utilizing these keywords effectively is essential for Salesforce developers and
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
administrators to extract meaningful insights and drive informed decision-making within their
organizations.
Reviews Contact Us
SELECT: Retrieves one or more fields from an object.
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/ 8/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
SELECT Id, Name FROM Account WHERE Industry NOT IN ('Retail', 'Healthcare')
SELECT Id, Name FROM Account WHERE Industry = 'Technology' AND AnnualRevenue > 100000
Whatsapp Chat
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 9/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
SELECT Id, Name FROM Account WHERE Industry = 'Technology' OR Industry = 'Finance'
Reviews Contact Us
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
Reviews Contact Us
Explanation:
1. SOQL Query: We are querying Contact records along with their related Account
information using a SOQL query. We use Account__r.Name and Account__r.Industry
to access fields from the related Account object. The _r signifies that we are traversing a
relationship.
2. Iteration: We loop through the queried Contact records using a for loop.
3. Accessing Fields: Within the loop, we access fields of both the Contact and its related
Account using dot notation ( . ). For example, contact.Account__r.Name accesses
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 11/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
Reviews Contactchild
// Printing Us Contact information
System.debug('Contact Name: ' + contactName);
System.debug('Contact Email: ' + contactEmail);
}
Explanation:
1. Parent Account ID: We define the ID of the parent Account record from which we want
2. SOQL Query: We use a SOQL query to retrieve child Contact records ( SELECT Id,
Name, Email FROM Contact WHERE AccountId = :parentAccountId ). We filter the
contacts based on the AccountId field, which represents the lookup relationship to the
parent Account .
3. Iteration: We loop through the queried child Contact records using a for loop.
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 .
5. Debugging: We print out information about each child Contact using System.debug()
Explanation:
1. Child Contact ID: We define the ID of the child Contact record for which we want to
fetch the related parent Account record. Replace 'Insert_Contact_ID_Here' with the
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, AccountId,
We use dot notation ( . ) to traverse the relationship and access fields from the parent
Account object.
3. Accessing Parent Fields: After executing the query, we access fields of the parent
Account from the related Contact record using dot notation ( . ). For example,
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 13/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
You can explore all the String methods in Apex, and learn those examples for each method.
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
Suppose we have a custom object called Opportunity with fields Amount (representing the
amount of the opportunity) and StageName (representing the stage of the opportunity). We
want to calculate the total amount of all opportunities and the average amount of
opportunities in each stage.
Explanation:
1. SOQL Query with Aggregate Functions: We use a SOQL query to perform aggregate
functions on the Opportunity object. We select the StageName field and calculate the
sum of Amount (totalAmount) and the average of Amount (avgAmount). We group the
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 14/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
4. Printing: We print out the stage name, total amount, and average amount for each stage
Watch our FREE Salesforce online course video, it’s a full length free tutorial for beginners.
In this example, searchKey is a binding variable. It is used in the SOQL query to dynamically
filter contacts by the last name specified in the searchKey variable.
Whatsapp Chat
String objectType = 'Contact'; // Object type to query
String fieldName = 'LastName'; // Field name to filter
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 15/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
Reviews Contact Us
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.
In DML statements like update , insert , delete , and upsert , binding variables are used
implicitly. In this example, accToUpdate is bound to the update operation, and its changes
are persisted to the database.
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.
Whatsapp Chat
How to start with SOQL?
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 16/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
To work on SOQL you must have records in the database. So, before starting working on
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
Soql follow the below steps to insert some records via apex.
Step 1: Open the developer console and click on the Debug tab to open the anonymous
Reviews Contact Us
window as shown below the image.
Step 2: In the image below, we have created an Account and associated contact and opportunity with it via apex.
Whatsapp Chat
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 17/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
Using the Query Editor, we can now write and execute a SOQL query to fetch the above-
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
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.
Reviews Contact Us
Read more: Validation Rules in Salesforce
In the image below we have queried the Account and its associated contact and opportunity
records and filtered the result by Account Name.
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
4. SOQl allows binding apex variables in the query to filter the records.
5. SOQl supports Parent to Child and Child to Parent queries.
Watch our FREE Salesforce online course video, it’s a full length free tutorial for beginners.
Whatsapp Chat
Frequently Asked Questions
What are the differences between SOQL, SOSL, and SQL?
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 18/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
SOSL, or Salesforce Object Search Language, is like a powerful tool I use to find stuff in
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
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
Reviews whatUsI need. So, instead of looking through each book one by one, SOSL
Contact
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’.
Whatsapp Chat
SOSL Query:
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 19/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
This SOSL query searches for the keyword ‘ACME’ across all fields of the Contact and
Reviews Contact Us
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.
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 call it from your
JavaScript code:
Whatsapp Chat
Apex Controller:
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 20/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
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 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 fromChat
Whatsapp the
“Account” object. It’s a simple yet powerful way to extract specific information from
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 21/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
Salesforce objects, and it forms the foundation for more complex queries involving additional
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
clauses like WHERE, ORDER BY, GROUP BY, and others.
How to find
Reviews
Object and Field API Names for your Queries?
Contact Us
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.
Navigate to the Developer Console by clicking on your profile picture and selecting
“Developer Console”.
Open the “Execute Anonymous Window” by clicking on “Debug” > “Open Execute
Anonymous Window”.
Enter the following Apex code to describe the Account object and its fields:
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 22/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
Click on “Execute” to run the code. The Developer Console will display the Field Label and
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
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
Reviews Contact Us
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';
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.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 23/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
involves writing the query directly within square brackets and assigning the result to a list
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
variable, as shown:
List<Account>
Reviews accounts
Contact Us = [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:
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 theChat
Whatsapp
retrieved data as needed within your Apex code. By leveraging SOQL in Apex, you can
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 24/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
effectively interact with Salesforce data and build robust applications on the Salesforce
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
platform.
Used for querying data from specific objects Used for performing text searches in records across
and their related objects. multiple objects.
Allows querying of individual records similar to Allows searching of fields with a search expression
SQL SELECT statements. using keywords.
Returns records that meet specific criteria Returns records containing the search term, potentially
defined in the WHERE clause. from multiple object types simultaneously.
Query targets a specific object or a specific set Searches the global index of all records that meet the
of objects defined in the FROM clause. search criteria across multiple objects.
Supports nested queries and relationship Limited to simple search conditions; does not allow
queries. nested queries or relationship queries.
Ideal for precise, complex queries where you Ideal for broad, text-based searches where the exact
know the structure of the database. location of data is unknown.
Can include COUNT, SUM, MAX, MIN, and Primarily focuses on finding text in record fields
other functions. without aggregate functions.
Has a row limit based on context, usually Has a different limit, typically 2,000 records for global
50,000 records in batch Apex. 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
Whatsapp Chat
need. Enroll for free demo today!
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 25/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
This exampleContact
Reviews demonstrates
Us how to retrieve account details for a specific customer using
their account ID.
This code defines a method getAccountDetails within the CustomerService class. The
method takes an account ID as a parameter and retrieves the corresponding account’s
details such as ID, name, billing address, phone, industry, and annual revenue using an
SOQL query.
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/ 26/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
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/ 27/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
Reviews Contact Us
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/ 28/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
This example fetches all appointments scheduled for a specific doctor within a specified date
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
range.
public class
Reviews AppointmentService
Contact Us {
public List<Appointment__c> getDoctorAppointments(Id doctorId, Date startDate, Da
List<Appointment__c> appointments = [SELECT Id, Doctor__c, Patient__c, Appoin
FROM Appointment__c
WHERE Doctor__c = :doctorId
AND Appointment_Date__c >= :startDate
AND Appointment_Date__c <= :endDate
ORDER BY Appointment_Date__c ASC];
return appointments;
}
}
This example demonstrates how to retrieve details for a specific flight using its flight number.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 29/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
This code defines a method getFlightDetails within the FlightService class. The
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
method takes a flight number as a parameter and retrieves the corresponding flight’s details
such as ID, flight number, departure city, arrival city, departure time, arrival time, and status
using an SOQL
Reviews query.
Contact Us
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.
Whatsapp Chat
public class ShipmentService {
public Shipment__c getShipmentDetails(Id shipmentId) {
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 30/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
This code defines a method getShipmentDetails within the ShipmentService class. The
method takes a shipment ID as a parameter and retrieves the corresponding shipment’s
details such as ID, shipment number, origin, destination, departure date, arrival date, and
status using an SOQL query.
This example fetches all deliveries assigned to a specific driver within a specified date range.
This code defines a method getDriverDeliveries within the DeliveryService class. The
method takes a driver ID, start date, and end date as parameters and retrieves all deliveries
assigned to that driver within the specified date range. The deliveries are ordered by delivery
date in ascending order. The fields retrieved include ID, driver reference, shipment reference,
delivery date, status, and destination.
This example fetches all courses offered by a specific department using the department ID.
Whatsapp
This code defines a method getDepartmentCourses within the CourseService Chat
class. The
method takes a department ID as a parameter and retrieves all courses offered by that
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 32/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
department. The courses are ordered by name in ascending order. The fields retrieved
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
include ID, name, department reference, credits, and course code.
Frequently
Reviews
Asked Questions (FAQs)
Contact Us
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 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 a
3. Integer: An integer value, usually returned when using aggregate functions like COUNT
Whatsapp Chat
to determine the number of records that match the query criteria.
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 33/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
In a single SOQL query, you can retrieve up to 50,000 records. This limit applies to the total
number of records returned by the query. If you need to process more records, you may
need to use pagination techniques or batch Apex to handle larger datasets efficiently.
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.
Whatsapp Chat
Read more: Classes – Salesforce Apex
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 34/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
Reviews
1. Contact Us
Basic Queries: Simple queries that retrieve data from a single object.
SELECT Id, Name FROM Account;
2. Relationship Queries: Queries that retrieve data from related objects using child-to-
parent or parent-to-child relationships.
In SOQL, you can query up to five levels of parent-child relationships in a single query.
However, there are some limitations on the number of parent-to-child subqueries you can
include. The query depth limit in Salesforce ensures that complex queries remain performant
and within governor limits.
1. Optimize Queries: Ensure your queries are efficient and retrieve only necessary fields
and records.
2. Reduce Loop Queries: Avoid placing SOQL queries inside loops. Instead, use bulk
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 35/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
3. Use Collections: Retrieve records in bulk and use collections (lists, sets, maps) to
Home About Us Courses Registration Interview Questions Free Salesforce Tutorials
process the data.
4. Use Batch Apex: For large data operations, consider using Batch Apex to process
Reviews Contact Us
records in manageable chunks.
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/ 36/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 37/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
Reviews Contact Us
Name *
Name
Email address *
Email address
Phone *
Phone
Select Course
Select Course/Service
Select Country/Location
Whatsapp Chat
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 38/39
11/7/24, 11:38 AM SOQL Query in Salesforce Apex & Examples
RECENT POSTS
Reviews Full Stack developer Interview Questions
Contact Us
Recent Posts
Whatsapp Chat
Terms of Use Privacy Policy Disclaimer Contact Us
https://www.crsinfosolutions.com/salesforce-apex-tutorial-chapter-19-apex-soql-query/ 39/39