SOSL Queries

5 minutes 5 Questions

SOSL (Salesforce Object Search Language) is a powerful search language in Salesforce that allows developers to perform text-based searches across multiple objects simultaneously. Unlike SOQL, which queries specific objects and fields, SOSL searches the entire search index, making it ideal for finding records across various objects when you don't know exactly where the data resides. **Syntax Structure:** A basic SOSL query follows this format: `FIND {searchTerm} IN searchGroup RETURNING ObjectType(fields)` For example: `FIND {Acme} IN ALL FIELDS RETURNING Account(Name, Phone), Contact(FirstName, LastName)` **Key Components:** - **FIND:** Specifies the search term, enclosed in curly braces. Supports wildcards (* and ?) for partial matching. - **IN:** Defines the search scope — ALL FIELDS, NAME FIELDS, EMAIL FIELDS, PHONE FIELDS, or SIDEBAR FIELDS. - **RETURNING:** Specifies which objects and fields to return in results. - **WITH:** Adds filters like WITH DATA CATEGORY or WITH NETWORK. - **LIMIT:** Restricts the number of results returned. **Important Considerations for Developers:** 1. SOSL returns a list of lists `(List<List<SObject>>)`, where each inner list corresponds to an object type specified in the RETURNING clause. 2. SOSL queries in Apex use `Search.query()` method or can be written inline with square brackets. 3. Governor limits allow up to 20 SOSL queries per transaction. 4. SOSL searches require at least two characters in the search term. 5. SOSL leverages Salesforce's search index, which may have a slight delay in indexing newly created or updated records. **When to Use SOSL vs SOQL:** - Use SOSL when searching across multiple objects or when performing text-based searches. - Use SOQL when you know which object contains the data and need precise field-level filtering with WHERE clauses. SOSL is particularly valuable in building global search functionality, custom search pages, and scenarios where users need to find records matching a keyword across the entire org efficiently.

SOSL Queries – Salesforce Platform Developer 1 Exam Guide

Why SOSL Queries Are Important

Salesforce Object Search Language (SOSL) is a critical topic on the Salesforce Platform Developer 1 exam, falling under the Process Automation and Logic domain. Understanding SOSL is essential because it allows developers to perform powerful text-based searches across multiple objects simultaneously — a capability that SOQL alone cannot efficiently provide. In real-world Salesforce development, SOSL is used for building search functionality, locating records across disparate objects, and optimizing user experiences when the exact object or field containing the data is unknown.

What Is SOSL?

SOSL (Salesforce Object Search Language) is a programmatic way to perform text searches across multiple standard and custom objects in Salesforce. Unlike SOQL, which queries specific objects and fields with precise filtering, SOSL searches the search index maintained by the Salesforce platform and returns results from multiple objects in a single query.

A basic SOSL query looks like this:

FIND {searchTerm} IN ALL FIELDS RETURNING Account(Name), Contact(FirstName, LastName)

Key components of the syntax:
- FIND: The required clause that specifies the search term enclosed in curly braces { }.
- IN: Specifies which fields to search. Options include ALL FIELDS, NAME FIELDS, EMAIL FIELDS, PHONE FIELDS, and SIDEBAR FIELDS. If omitted, the default is ALL FIELDS.
- RETURNING: Specifies which objects and fields to return in the results. This is optional — if omitted, the search returns IDs for all searchable objects.
- WITH: Optional clause for additional filtering (e.g., WITH NETWORK = 'networkId', WITH SNIPPET, WITH DATA CATEGORY).
- LIMIT: Optional clause to restrict the number of results returned.
- ORDER BY: Optional clause to sort results within each object's result set.

How SOSL Works

1. Search Index: SOSL queries do not scan database tables directly. Instead, they leverage the Salesforce search index, which is built and maintained asynchronously. This means newly inserted or updated records may not appear in SOSL results immediately (there can be a slight delay, typically a few minutes in production, though in test contexts this is handled differently).

2. Return Type: In Apex, a SOSL query returns a List<List<SObject>>. Each inner list corresponds to the objects specified in the RETURNING clause, in the same order. For example:

List<List<SObject>> results = [FIND 'Acme' IN ALL FIELDS RETURNING Account(Name), Contact(FirstName, LastName)];

Here, results[0] contains the list of Account records, and results[1] contains the list of Contact records.

3. Governor Limits: SOSL queries are subject to governor limits. A single SOSL query can return up to 2,000 records per object by default. You are limited to 20 SOSL queries per Apex transaction.

4. Wildcards: SOSL supports wildcards. The * wildcard matches zero or more characters at the middle or end of a search term (e.g., 'Acm*'). The ? wildcard matches exactly one character (e.g., 'Ac?e'). The minimum search term length is 2 characters when using wildcards.

5. Search Term Requirements: The search term in a FIND clause must be at least 2 characters long. Single-character searches are not permitted.

6. Searchable Fields: Not all fields are searchable via SOSL. Generally, fields of type Text, Text Area, Long Text Area, Rich Text Area, Email, Phone, and Name are indexed and searchable. Fields like Number, Date, Checkbox, and Lookup/ID fields are not searchable through SOSL.

SOSL vs. SOQL: Key Differences

Understanding when to use SOSL versus SOQL is a frequently tested concept:

- Use SOQL when you know which object and field the data resides in, when you need to retrieve records from a single object (or related objects via relationships), when you need to count records, or when you need to sort or aggregate data.
- Use SOSL when you don't know which object or field contains the data, when you need to search across multiple unrelated objects simultaneously, when you need to perform a text-based search efficiently, or when searching across many fields at once.

SOSL in Apex

SOSL queries can be executed in Apex using the following approaches:

1. Inline SOSL (static): Enclosed in square brackets like SOQL.
List<List<SObject>> results = [FIND 'Acme' IN ALL FIELDS RETURNING Account, Contact];

2. Dynamic SOSL: Using the Search.query() method for dynamically constructed search strings.
String searchQuery = 'FIND \'Acme\' IN ALL FIELDS RETURNING Account(Name), Contact(LastName)';
List<List<SObject>> results = Search.query(searchQuery);

SOSL in Tests

An important exam concept: In Apex test methods, SOSL queries return empty results by default. To make SOSL return specific records in tests, you must use Test.setFixedSearchResults() and pass a list of record IDs that should be returned by any SOSL queries executed during the test. For example:

Account acc = new Account(Name='Test Acme');
insert acc;
Test.setFixedSearchResults(new List<Id>{acc.Id});
List<List<SObject>> results = [FIND 'Acme' RETURNING Account];
// results[0] will now contain the acc record

This is a very commonly tested concept. Without Test.setFixedSearchResults(), SOSL in test methods returns no results regardless of what data exists.

RETURNING Clause Details

Within the RETURNING clause, you can apply additional filtering per object using WHERE, ORDER BY, and LIMIT:

FIND 'Acme' IN ALL FIELDS RETURNING Account(Name, Industry WHERE Industry = 'Technology' ORDER BY Name LIMIT 10), Contact(FirstName, LastName)

This provides fine-grained control over what is returned from each object.

WITH Clauses

SOSL supports several WITH clauses for additional control:
- WITH DATA CATEGORY: Filter Knowledge articles by data category.
- WITH SNIPPET: Return highlighted text snippets showing where the search term was found.
- WITH SPELL_CORRECTION: Enable or disable spell correction on the search term.
- WITH DIVISION: Filter by division (for orgs using divisions).

Escape Characters

Special characters in SOSL search terms must be escaped with a backslash. Reserved characters include: ? & | ! { } [ ] ( ) ^ ~ * : \ ' + -. In Apex strings, because backslash itself is an escape character, you need double backslashes. For example, to search for the term Acme & Co:
String searchTerm = 'Acme \& Co';

Exam Tips: Answering Questions on SOSL Queries

1. Know the return type: SOSL always returns List<List<SObject>>. If an exam question asks about the return type or shows code assigning SOSL results to a different type, it is incorrect.

2. Understand SOSL vs. SOQL scenarios: The exam frequently presents scenarios and asks whether SOSL or SOQL is more appropriate. Remember: unknown object/field → SOSL; known object/field → SOQL; need aggregation → SOQL; cross-object text search → SOSL.

3. Test.setFixedSearchResults(): Expect questions about testing SOSL. The correct answer almost always involves using Test.setFixedSearchResults(). Without it, SOSL returns no results in tests.

4. Governor limits: Remember 20 SOSL queries per transaction and 2,000 records returned per object. These numbers appear in exam questions.

5. Curly braces around search term: The FIND clause uses curly braces { }, not single quotes, in inline SOSL. In dynamic SOSL (string), single quotes are used around the search term: FIND 'term'.

6. Searchable field types: If a question asks about searching Number, Date, or Checkbox fields, SOSL is not the right tool — SOQL should be used instead.

7. Watch for the IN clause: Questions may test whether you know the valid values for the IN clause: ALL FIELDS, NAME FIELDS, EMAIL FIELDS, PHONE FIELDS, SIDEBAR FIELDS. ALL FIELDS is the default.

8. Accessing results: Results are accessed by index matching the order of objects in the RETURNING clause. If the RETURNING clause lists Account first and Contact second, results[0] = Accounts and results[1] = Contacts.

9. Dynamic SOSL: Use Search.query() for dynamic SOSL, not Database.query() (which is for dynamic SOQL). This is a common trap in exam questions.

10. Minimum search term length: SOSL requires at least 2 characters in the search term. Questions may present single-character searches as distractors.

11. No DML before SOSL in synchronous context: Because SOSL relies on the search index, records inserted in the same transaction may not be found by SOSL (except in tests using Test.setFixedSearchResults). This distinction is sometimes tested.

12. Practical Tip: When reading exam questions, look for keywords like "search," "find across multiple objects," "text search," or "don't know which object" — these strongly suggest SOSL is the correct approach. Conversely, keywords like "query," "retrieve specific records," "filter by date," or "aggregate" point toward SOQL.
Test mode:

PD1 - SOSL Queries Example Questions

Test your knowledge of SOSL Queries

Question 1

A developer is new to Salesforce and needs to search for the term 'Global' across Account and Contact records. They write the following code: String searchTerm = 'Global'; List<List<SObject>> results = [FIND :searchTerm IN ALL FIELDS RETURNING Account(Name), Contact(FirstName, LastName)]; What type of data structure does the variable 'results' hold after the query executes?

Question 2

A developer writes the following SOSL query in Apex: List<List<SObject>> results = [FIND 'Acme*' IN NAME FIELDS RETURNING Account(Name, Industry), Contact(FirstName, LastName)]; The developer wants to extract all matching Contact records from the results. Which code correctly retrieves the Contact records?

Question 3

A developer needs to find records containing the word 'Solar' across both Account and Contact objects. They write the following code: List<List<SObject>> results = [FIND 'Solar' IN ALL FIELDS RETURNING Account(Name), Contact(FirstName, LastName)]; How many elements does the outer list contain after this query executes?

More SOSL Queries questions
47 questions (total)