SOQL Query Examples: A Comprehensive Guide

Photo of author
Jerome Clatworthy

Certified Salesforce Administrator

If you’re a Salesforce developer or Administrator, you’re probably familiar with Salesforce Object Query Language (SOQL). SOQL is a powerful tool that enables you to retrieve data from Salesforce databases. It is similar to SQL in many ways, but it is designed specifically for Salesforce.

In this article, I will provide you with some practical examples of SOQL queries that you can use to retrieve data from Salesforce databases.

I’ll cover some basic queries and then move on to more advanced queries that will help you get the most out of your data.

By the end of this article, you’ll have a better understanding of how to use SOQL to retrieve the data you need from Salesforce databases.

Basic SOQL Query Examples

If you’re new to SOQL, it’s important to start with the basics. In this section, I’ll cover some basic SOQL query examples to help you get started.

SELECT Statement

The SELECT statement is used to retrieve data from one or more fields in a specified object. Here’s an example of a basic SELECT statement:

SELECT Id, Name, Email FROM Contact

In this example, we’re selecting the Id, Name, and Email fields from the Contact object. You can add or remove fields as necessary to retrieve the data you need.

FROM Clause

The FROM clause is used to specify the object you want to retrieve data from. Here’s an example of a basic FROM clause:

SELECT Id, Name FROM Account

In this example, we’re retrieving the Id and Name fields from the Account object.

WHERE Clause

The WHERE clause is used to filter the data you retrieve based on specific criteria. Here’s an example of a basic WHERE clause:

SELECT Id, Name FROM Account WHERE Industry = 'Technology'

In this example, we’re retrieving the Id and Name fields from the Account object where the Industry field equals ‘Technology’. You can use other operators such as LIKE, IN, and NOT IN to further refine your query.

Overall, these basic SOQL query examples should give you a good foundation for building more complex queries.

KEY CONCEPT

Remember to always start with the SELECT statement, specify the object in the FROM clause, and filter your data using the WHERE clause when necessary.

Advanced SOQL Query Examples

If you’re looking to take your SOQL queries to the next level, you’ll want to start incorporating advanced operators into your queries.

In this section, I’ll go over some examples of how to use the In, Or, and Like operators in your SOQL queries.

IN Operator

The IN operator is used to match a value against a list of values. This is useful when you want to match a field against multiple values. For example, if you want to find all accounts where the Industry is either “Technology” or “Finance”, you can use the IN operator:

SELECT Name, Industry FROM Account WHERE Industry IN ('Technology', 'Finance')

This query will return all accounts where the Industry field is either “Technology” or “Finance”.

OR Operator

The OR operator is used to combine multiple conditions in a single query. This is useful when you want to match a field against multiple conditions. For example, if you want to find all accounts where the Industry is either “Technology” or the Rating is “Hot”, you can use the OR operator:

SELECT Name, Industry, Rating FROM Account WHERE Industry = 'Technology' OR Rating = 'Hot'

This query will return all accounts where the Industry field is “Technology” or the Rating field is “Hot”.

LIKE Operator

The Like operator is used to match a field against a pattern. This is useful when you want to match a field against a partial value.

For example, if you want to find all accounts where the Name field starts with “Acme”, you can use the Like operator:

SELECT Name, Industry FROM Account WHERE Name LIKE 'Acme%'

This query will return all accounts where the Name field starts with “Acme”.

By using these operators, you can match fields against multiple values or conditions, or match fields against partial values.

Sorting and Limiting SOQL Results

When querying data from Salesforce, you may want to sort the results or limit the number of records returned. The Order By and Limit clauses in SOQL can help you achieve this.

ORDER BY Clause

The Order By clause in SOQL is used to sort the query results in ascending or descending order. You can sort records based on one or more fields by specifying the field names separated by commas.

For example, to sort Account records by Name in ascending order, you can use the following query:

SELECT Id, Name FROM Account ORDER BY Name ASC

In this query, the ORDER BY clause is used to sort the results by the Name field in ascending order. You can also use the DESC keyword to sort the results in descending order.

For example:

SELECT Id, Name FROM Account ORDER BY Name DESC

This query will sort the results by the Name field in descending order.

LIMIT Clause

The LIMIT clause in SOQL is used to limit the number of records returned by a query. This is useful when dealing with large datasets or when you only need a specific number of records.

You can specify the maximum number of records to return by using the LIMIT keyword followed by a number.

For example, to return the first 10 Account records, you can use the following query:

SELECT Id, Name FROM Account LIMIT 10

In this query, the LIMIT clause is used to limit the results to the first 10 records.

KEY CONCEPT

It’s important to note that the LIMIT clause only limits the number of records returned by the query, not the number of records that are processed by the query.

If your query includes a filter that matches a large number of records, the query may still take a long time to execute even with a LIMIT clause.

Working with Specific Objects in SOQL

When working with SOQL, it is essential to know how to work with specific objects. Here are some examples of how to work with the Account, Contacts, and Sales objects in SOQL.

Account Object

The Account object is used to store information about your customers or clients. You can use SOQL to retrieve information about accounts, such as their name, address, and phone number. Here is an example of a simple SOQL query that retrieves all account records:

SELECT Id, Name, Phone, BillingCity FROM Account

This query retrieves the Id, name, phone number, and billing city of all account records.

Contacts Object

The Contacts object is used to store information about the people associated with your accounts. You can use SOQL to retrieve information about contacts, such as their name, email address, and phone number. Here is an example of a simple SOQL query that retrieves all contact records:

SELECT Id, FirstName, LastName, Email FROM Contact

This query retrieves the Id, first name, last name, and email address of all contact records.

Sales Object

The Sales object is used to store information about your sales opportunities. You can use SOQL to retrieve information about sales, such as the opportunity name, amount, and close date.

Here is an example of a simple SOQL query that retrieves all sales records:

SELECT Id, Name, Amount, CloseDate FROM Opportunity

This query retrieves the Id, name, amount, and close date of all sales records.

By using SOQL, you can easily retrieve information about your accounts, contacts, and sales records to help you manage your customer relationship management (CRM) data.

Data Analysis with SOQL

When it comes to data analysis, SOQL has a lot to offer. You can use various functions and clauses to manipulate and analyze data.

In this section, I will explain some of the most useful functions for data analysis in SOQL.

COUNT Function

The COUNT() function is used to count the number of records returned by a query. You can use it to count the total number of records in a table or the number of records that meet a specific condition.

For example, if you want to count the number of opportunities that are closed, you can use the following query:

SELECT COUNT() FROM Opportunity WHERE IsClosed = true

This query will return the total number of closed opportunities. You can also use the GROUP BY clause to group the results by a specific field. For example, if you want to count the number of closed opportunities by stage, you can use the following query:

SELECT StageName, COUNT() FROM Opportunity WHERE IsClosed = true GROUP BY StageName

This query will return the number of closed opportunities for each stage.

DATE Functions

SOQL provides several date functions that you can use to manipulate and analyze dates. Here are some of the most commonly used date functions:

  • TODAY(): Returns the current date.
  • YEAR(): Returns the year of a date.
  • MONTH(): Returns the month of a date.
  • DAY(): Returns the day of a date.

You can use these functions to filter records by date or to group records by date. For example, if you want to find all opportunities that were created today, you can use the following query:

SELECT Id, Name FROM Opportunity WHERE CreatedDate = TODAY()

This query will return all opportunities that were created today.

SOQL in Salesforce Development

In this section, I will explore how you can use SOQL in Salesforce development.

Apex Code

Apex is a programming language used by Salesforce developers to build custom applications on the Salesforce platform. In Apex, you can use SOQL to retrieve data from the Salesforce database.

To use SOQL in Apex, you can use the Database.query() method. Here is an example of how to use SOQL in Apex:

List<Account> accounts = [SELECT Id, Name FROM Account WHERE Industry = 'Technology'];

In the above example, we are retrieving all accounts where the Industry equals ‘Technology’. We are only retrieving the Id and Name fields of the Account object.

Developer Console

The Developer Console is a powerful tool that allows you to write, execute, and debug code in Salesforce. In the Developer Console, you can use the Query Editor to write and execute SOQL queries.

Here is an example of how to use the Query Editor to execute a SOQL query:

  1. Open the Developer Console.
  2. Click on the Query Editor tab.
  3. Enter your SOQL query in the Query Editor.
  4. Click the Execute button to execute the query.

Query Editor

The Query Editor is a feature of the Developer Console that allows you to write and execute SOQL queries.

In the Query Editor, you can also view the query results and export them to a CSV file. Here are some tips for using the Query Editor:

  • Use the autocomplete feature to help you write your queries faster
  • Use the Explain feature to see how Salesforce executes your query
  • Use the Query Plan feature to see how Salesforce optimizes your query

SOQL and Data Management

When working with Salesforce data, SOQL is the go-to language for querying and retrieving data.

However, SOQL can also be used for data management tasks, such as data pipelines, data transformation, and DML operations.

DML Operations

DML (Data Manipulation Language) operations allow you to modify data in your Salesforce org. With SOQL, you can perform DML operations like insert, update, upsert, merge, and delete.

These operations let you create, update, or delete records in your org. You can also perform bulk DML operations to process large amounts of data.

Data Pipelines

Data pipelines are used to move data from one system to another. With SOQL, you can create data pipelines to extract data from Salesforce and load it into another system.

This can be done using the Salesforce API, which allows you to retrieve data using SOQL queries and then push it to another system.

Data Transformation

Data transformation refers to the process of converting data from one format to another. With SOQL, you can transform data by using functions like CASE, CAST, and CONVERT.

These functions allow you to manipulate data to meet your specific requirements.

Integration and Services

When it comes to integrating Salesforce with other systems and services, SOQL queries play a crucial role. In this section, we will discuss various integration and service options that work well with SOQL queries.

Connector Availability

Salesforce offers a wide range of connectors that allow you to integrate with other systems and services seamlessly.

These connectors include the Salesforce Connector for MuleSoft, the Salesforce Connector for Informatica, the Salesforce Connector for SAP, and many more.

These connectors are designed to work with SOQL queries, making it easy to extract and manipulate data from Salesforce.

SaaS Applications

In addition to on-premises systems, many organizations use SaaS applications to manage their business operations. Fortunately, Salesforce offers a wide range of connectors for popular SaaS applications such as NetSuite, Workday, and Microsoft Dynamics.

These connectors make it easy to integrate your Salesforce data with other SaaS applications, allowing you to streamline your business processes and improve productivity.

Databases

If you need to integrate Salesforce with a database, there are several options available. One popular option is to use ODBC or JDBC drivers to connect to your database. These drivers allow you to execute SQL queries, including SOQL queries, against your database from within Salesforce.

Another option is to use a middleware platform such as MuleSoft or Informatica to connect Salesforce to your database. These platforms provide a more robust integration solution and allow you to transform data as it moves between systems.

Advanced Topics in SOQL

SOQL Join Objects

In some cases, you may need to retrieve data that is stored across multiple objects. SOQL allows you to join objects together to retrieve this data. When joining objects in SOQL, you use the JOIN keyword followed by the name of the object you want to join.

For example, if you want to join the Opportunity object with the Account object, you would use the following query:

SELECT Name, Amount, Account.Name FROM Opportunity JOIN Account ON Opportunity.AccountId = Account.Id

This query retrieves the Name and Amount fields from the Opportunity object, as well as the Name field from the Account object. The ON keyword is used to specify the join condition, which in this case is the AccountId field on the Opportunity object matching the Id field on the Account object.

Parentheses Usage

SOQL allows the use of parentheses to group conditions together. This can be useful when you need to specify more complex conditions. For example, if you want to retrieve all cases that are open or closed and have a priority of high or urgent, you would use the following query:

SELECT Id, CaseNumber, Priority FROM Case WHERE (IsClosed = false OR IsClosed = true) AND (Priority = 'High' OR Priority = 'Urgent')

In this query, the parentheses group the IsClosed conditions together and the Priority conditions together. This ensures that the correct logical order of operations is followed.

Other Advanced Topics

Other advanced topics in SOQL include sorting, using numbers, and querying data from various entities such as users, marketing, and customer relationship management (CRM). For more information on these topics, please refer to the Salesforce SOQL documentation.