Queries

Apex SOSL Queries

Using SOSL in Apex

Apex SOSL queries search across multiple Salesforce objects.

Introduction to SOSL Queries

Salesforce Object Search Language (SOSL) is used to perform text searches within your organization's Salesforce data. Unlike SOQL, which can only query one object at a time, SOSL allows you to search across multiple objects and fields. This makes SOSL highly efficient for finding data that may be dispersed across different areas of your Salesforce instance.

Basic Syntax of SOSL Queries

SOSL queries begin with the FIND keyword, followed by the search term within curly braces. The search term can be a word or phrase. You can then specify the fields to search within and the objects to search from. Here's a basic SOSL query syntax:

Executing SOSL Queries in Apex

You can execute SOSL queries directly in Apex by using the Database.query method. Below is an example of how to perform a SOSL query in an Apex class:

Use Cases for SOSL

SOSL is particularly useful in scenarios where you need to:

  • Search for records across multiple objects at once.
  • Quickly retrieve records based on a keyword or phrase.
  • Implement global search functionality within a Salesforce application.

It is important to consider the efficiency of SOSL, especially when dealing with large datasets, as it may return a large number of results.

Limitations and Considerations

While SOSL is powerful, there are limitations to be aware of:

  • SOSL queries return a limited number of records by default (2000 records across all objects).
  • They do not support aggregate functions like COUNT() or SUM().
  • SOSL does not support querying on fields with relationship names (e.g., Account.Name).

Understanding these limitations can help you make informed decisions when choosing between SOSL and other query languages available in Salesforce.

Queries