How to Query Data in Salesforce Using SOQL and SOSL

May 10, 2025
520 Views
How to Query Data in Salesforce Using SOQL and SOSL

Welcome to day 5 of the 10 day Apex series. In this blog, we will walk through the basics of powerful query language, share some examples and explain when to use each of them.

Whether you are just starting out or need a refresher on querying data in Salesforce, this blog is designed to be clear, approachable with useful insights. Salesforce data can feel complicated or vast at first, but it can become manageable and accessible easily once we learn how to query data effectively using SOQL and SOSL.

Starting With SOQL

SOQL stands for ‘Salesforce Object Query Language’. It is similar to SQL but is customized to navigate Salesforce’s data model. With SOQL, we can retrieve data from one or more objects that are related to each other, which makes it an essential tool for any Salesforce developer to retrieve data from our org.

Basic SOQL Queries

A basic SOQL query looks a lot like a SQL query. For example, if we want to fetch the Id and Name of every Account record, we can write as below:

List<Account> accounts = [SELECT Id, Name FROM Account];
System.debug(accounts);

The above query is easy and straightforward, it will select two fields (Id and Name ) from the Account object. The results are stored in a list of accounts and then logged using System.debug.

SOQL with WHERE Clauses to Filter Results

If we will need to narrow down our query to specific records using a WHERE clause based on business requirements. Consider below example to understand it:

List<Account> accounts = [SELECT Id, Name FROM Account];
System.debug(accounts);

In the above query, only accounts with the IsActive field set to true are returned. This simple filter is useful when we only want to work with a subset of data.

Sorting Our Results

To improve the results of our query based on ascending or descending order, we will need to sort them. The ORDER BY clause will help us to achieve it. Below is the example of how we could sort the accounts alphabetically by name:

List<Account> sortedAccounts = [SELECT Id, Name FROM Account ORDER BY Name ASC];
System.debug(sortedAccounts);

By using ORDER BY Name ASC, we can make sure that the list of accounts is sorted in ascending order based on the account name.

Advanced SOQL Queries

As we move ahead, we might come to complex scenarios that will require advanced or complex queries. These can involve relationships, aggregate functions or even subqueries with related objects.

Querying Relationships

Salesforce data is basically relational. To query related data, we can use relationship queries. For instance, if we want to fetch contacts related to an account, we will get it by below query:

List<Account> accountsWithContacts = [SELECT Id, Name, (SELECT Id, LastName FROM Contacts) FROM Account];
System.debug(accountsWithContacts);

Above SOQL fetches accounts along with their related contacts. Check the subquery inside parentheses; it retrieves the Id and LastName for each contact associated with an account.

Aggregate Functions

SOQL supports aggregate functions such as COUNT(), SUM(), AVG(), MIN() and MAX(). These functions are useful when we need summary information about the data we are retrieving. For example, to count the number of contacts we can write as below:

AggregateResult[] contactCount = [SELECT COUNT(Id) cnt FROM Contact];
for (AggregateResult ar : contactCount) {
    System.debug('Total Contacts: ' + ar.get('cnt'));
}

The COUNT() function returns the total number of contact records and we loop through the result to print that value.

Subqueries

Subqueries allow us to fetch detailed information from related objects in a single query. This might appear slightly more complex but the basic idea will be simple only. In below query, we will pull detailed orders for each account assuming we have custom order object:

List<Account> accountsWithOrders = [SELECT Id, Name, (SELECT OrderNumber, TotalAmount FROM Orders__r) FROM Account];
System.debug(accountsWithOrders);

In this example, (SELECT OrderNumber, TotalAmount FROM Orders__r) is a subquery that retrieves details from a child relationship (assuming the child relationship is named as Orders__r ).

Also Read

Don’t forget to checkout: Control Structures in Apex: How to Use If-Else and Loops.

Introduction to SOSL

SOSL is the abbreviation of ‘Salesforce Object Search Language’, is different compared to SOQL to get the data from our org. Instead of focusing on a single object or relationship, SOSL is designed for searching across multiple objects at a time or in a single query.

Use of SOSL

SOSL is useful when we need to perform text-based searches or search across multiple objects at a time that we are not sure which object the search can find. It is useful for creating search functionalities inside custom applications.

Basic SOSL Query

A basic SOSL query looks for a term/name across all fields of an object. For example, to search for the term “Salesforce” in any searchable field of the Account object, we will be writing SOSL as below:

List<List<SObject>> searchResults = 
    [FIND {Salesforce} IN ALL FIELDS RETURNING Account(Id, Name)];
System.debug(searchResults);

In this SOSL query:

  • FIND {Salesforce} is the search string.
  • IN ALL FIELDS directs SOSL to search in every field that is searchable.
  • RETURNING Account(Id, Name) specifies that the results should include the Id and Name fields from the Account object.

Searching Multiple Objects

One of the good ways of SOSL is its ability to search across multiple objects simultaneously. Below is an simple example of it:

List<List<SObject>> multiResults = 
    [FIND {Salesforce} IN ALL FIELDS 
     RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)];
System.debug(multiResults);

Above SOSL will search for the term “Salesforce” in both the Account and Contact objects, returning mentioned in SOSL fields from each. It is an easy way to perform a broad search without writing multiple queries.

Making It All Together

Both SOQL and SOSL are essential for accessing and managing our Salesforce data. Below is a simple scenario that illustrates how we use both query languages in our code as per the business requirements.

Imagine we are tasked or required with creating a feature for a Salesforce app that needs to display details about accounts and let users search for records quickly.

Example: Combining SOQL and SOSL


public class SalesforceDataQuery {
    // Below method will retrieve all active accounts sorted by name
    public static List<Account> getActiveAccounts() {
        return [SELECT Id, Name FROM Account WHERE IsActive = true ORDER BY Name ASC];
    }

    // Below method uses SOSL to search for a keyword across multiple objects
    public static List<List<SObject>> searchKeyword(String searchTerm) {
        return [FIND :searchTerm IN ALL FIELDS RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)];
    }

    public static void demoQueryFunctions() {
        // Retrieve and log active accounts
        List<Account> activeAccounts = getActiveAccounts();
        System.debug('Active Accounts: ' + activeAccounts);

        // Search for a keyword and log results
        List<List<SObject>> searchResults = searchKeyword('Salesforce');
        System.debug('Search Results: ' + searchResults);
    }
}

In above example:

  • getActiveAccounts() uses SOQL to fetch active accounts.
  • searchKeyword() uses SOSL to search for a keyword across the Account and Contact objects.
  • demoQueryFunctions() uses both methods, showing us how these queries can be used into our Salesforce application.

Conclusion

Using SOQL and SOSL let us get a world of possibilities in our Salesforce development journey. SOQL is our go to for structured data retrieval, Either it is a simple or a complex query involving relationships and aggregates. SOSL will offer us flexibility for text searches and multi-object queries at a time and will make it a useful tool for building effective searches in our org for playing with data.

This is Day 5 of the Apex 10-Day Series: How to Query Data in Salesforce Using SOQL and SOSL.

Up next on Day 6, we’ll dive into DML Operations and Exception Handling. Stay tuned and Happy coding!

Written by

user

Mohit Bansal

Salesforce Technical Architect | Lead | Salesforce Lightning & Integrations Expert | Pardot | 5X Salesforce Certified | App Publisher | Blogger

Contributor of the month
contributor
Gopinath G

Passionate about the intersection of cutting-edge technologies

Get the latest tips, news, updates, advice, inspiration, and more….

...
Boost Your Brand's Visibility

Want to promote your products/services in front of more customers?

...