SOSL Query in Salesforce Apex

SOSL Query in Salesforce Apex

On January 26, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on SOSL Query in Salesforce Apex
SOSL Query Salesforce Apex
SOSL Query in Salesforce Apex

Table of Contents

What is SOSL?

Salesforce Object Search Language (SOSL) is used to perform text searches in Salesforce records. Using SOSL, you can search fields across multiple standard and custom objects in Salesforce.

A SOSL query returns a list of lists of sObjects, where each list contains the results from the search for a particular sObject type. A SOSL query always returns results in the same order that was specified in the SOSL query. Whenever a SOSL query does not return any record for a specified sObject type, it is returned as an empty list in the search results.

  1. Purpose and Efficiency: SOSL is designed to help developers quickly find specific phrases or words across multiple objects in Salesforce, primarily searching within name, phone, and email fields to streamline data retrieval.
  2. Focus on Object Level: Unlike other search tools that may target single objects, SOSL queries multiple objects at the object level, returning results in a structured format that is both predictable and easy to manage.
  3. Result Structure: The results from a SOSL query are presented as a “list of lists” of sObjects, where each list corresponds to a specific sObject type included in the query, maintaining the order in which they were searched.
  4. Handling of No Results: In cases where a SOSL query finds no records for a specified sObject type, it provides an empty list for that type, ensuring consistent result structure and allowing developers to easily handle scenarios with no data.

How to write SOSL query?

1. Basic Query Structure

A basic SOSL query consists of the FIND clause, which specifies the text expression to search for, and the IN clause, which specifies the fields to search within. The RETURNING clause specifies the object(s) and fields from which to retrieve data.

Example:

FIND {John} 
IN Name Fields 
RETURNING Contact(Id, Name, Email), Account(Id, Name)

This query searches for the term “John” in the Name fields of both Contact and Account objects, and it retrieves the Id, Name, and Email of contacts and Id and Name of accounts.

2. Using Wildcards

You can use wildcards to broaden your search. The asterisk ( * ) represents zero or more characters, and the question mark ( ? ) represents exactly one character.

Example:

FIND {Sm?th*} 
IN Name Fields 
RETURNING Account(Id, Name)

This searches for names like ‘Smith’, ‘Smyth’, etc., followed by any sequence of characters.

3. Searching in All Fields

If you want to search all text fields, use ALL FIELDS .

Example:

FIND {Acme} 
IN ALL FIELDS 
RETURNING Account(Id, Name), Contact(Id, Name)

This query searches all text fields for “Acme” in both Account and Contact objects.

4. Specifying Conditions and Limits

You can add conditions and limits to the RETURNING clause to refine your results.

Example:

FIND {Joe} 
IN Name Fields 
RETURNING Contact(Id, Name WHERE LastName='Bloggs' AND Department='Sales' LIMIT 10)

This searches for “Joe” in Contact names but only where the last name is “Bloggs” and the department is “Sales”. It limits the results to 10 records.

5. Dynamic SOSL

You can also construct SOSL queries dynamically in Apex code, which is useful for building search functionalities in applications.

Example:

String searchQuery = 'FIND \'*' + searchString + '*\' IN ALL FIELDS RETURNING Account(Id, Name), Contact(Id, Name)';
List<List<SObject>> searchList = Search.query(searchQuery);

In this Apex code example, searchString is a variable holding the user input which is included in the SOSL query.

Best Practices

  • Use SOSL when you need to search across multiple objects or when you don’t know which object or field the data resides in.
  • SOSL can return a large number of records; make sure to use WHERE and LIMIT clauses to narrow down the results and prevent performance issues.
  • Remember that SOSL respects field-level security. Ensure your application handles scenarios where users may not have permission to see all search results.

Difference between SOQL and SOSL

SOQL (Salesforce Object Query Language)SOSL (Salesforce Object Search Language)
Used for querying data from specific objects and their related objects.Used for performing text searches in records across multiple objects.
Allows querying of individual records similar to SQL SELECT statements.Allows searching of fields with a search expression using keywords.
Returns records that meet specific criteria defined in the WHERE clause.Returns records containing the search term, potentially from multiple object types simultaneously.
Query targets a specific object or a specific set of objects defined in the FROM clause.Searches the global index of all records that meet the search criteria across multiple objects.
Supports nested queries and relationship queries.Limited to simple search conditions; does not allow nested queries or relationship queries.
Ideal for precise, complex queries where you know the structure of the database.Ideal for broad, text-based searches where the exact location of data is unknown.
Can include COUNT, SUM, MAX, MIN, and other functions.Primarily focuses on finding text in record fields without aggregate functions.
Has a row limit based on context, usually 50,000 records in batch Apex.Has a different limit, typically 2,000 records for global search across objects.
Difference between SOQL and SOSL

SOSL Syntax

SOSL (Salesforce Object Search Language) syntax allows developers to construct queries that search across multiple objects efficiently. Here’s an overview of the basic syntax and an example to demonstrate how it works:

Basic Syntax of SOSL:

FIND {searchQuery} IN {searchGroup} RETURNING {objectType}(fieldList [WHERE condition] [ORDER BY fieldList] [LIMIT n])
  • {searchQuery}: The text phrase or word you want to search for, enclosed in single quotes.
  • {searchGroup}: Specifies where to perform the search, such as in ALL FIELDS, NAME FIELDS, EMAIL FIELDS, or PHONE FIELDS.
  • {objectType}: The type of object to retrieve, like Account , Contact , etc.
  • fieldList: Specifies the fields to retrieve from the search results.
  • WHERE condition (optional): Adds a condition to filter results.
  • ORDER BY fieldList (optional): Specifies the order of the returned records.
  • LIMIT n (optional): Limits the number of results returned.

Example of a SOSL Query:

FIND 'Acme*' IN NAME FIELDS RETURNING Account(Id, Name WHERE Name LIKE 'Acme%' ORDER BY Name LIMIT 10), Contact(Id, LastName, FirstName WHERE LastName LIKE 'Acme%')

In this example:

  • *FIND ‘Acme‘**: Searches for records that start with “Acme”.
  • IN NAME FIELDS: Limits the search to name fields across objects.
  • RETURNING: Specifies that results should include records from the Account and Contact sObjects.
    • For Account , retrieves the Id and Name where the name starts with “Acme”, sorts the results by name, and limits to 10 records.
    • For Contact , retrieves the Id , LastName , and FirstName where the last name starts with “Acme”.

Let’s take an example that searches the text ‘Salesforce’ in Account, Contact, and opportunity fields.

List<List<sObject>> searchList = [FIND 'Salesforce' IN ALL FIELDS 
 RETURNING Account(Name,Industry WHERE Industry='Chemical' LIMIT 1),Contact(FirstName,LastName),Opportunity(Name)];

Next chapter is SOQL Query and previous chapter is database methods.

CRS Info Solutions offers a comprehensive and dynamic Salesforce certification course career building program for beginners, covering admin, developer, and LWC concepts. This course features immersive real-time projects, interactive hands-on learning, detailed daily notes, essential interview questions, thorough certification preparation, and strategic job prep 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. Enroll for a free demo today!

Comments are closed.