Skip to content

Exploring Salesforce Object Search Language (SOSL): Limits and Apex Integration

SOSL Hero Image

Understanding the limitations of SOSL is crucial for designing efficient and effective search queries. SOSL (Salesforce Object Search Language) limits the number of search results it can return to ensure platform efficiency.

A single SOSL query can return up to 2,000 records (version 28.0 and above). When querying a single object, up to 250 records are returned unless a WHERE or ORDER BY clause is used, which can then return up to 2,000 records. In multi-object queries, each object can return up to the lesser of 250 records or 2,000 divided by the number of objects. For example, if you query 10 objects, each object can return up to 200 records.

The LIMIT clause can be applied per object in the RETURNING statement or globally for the entire query. However, it cannot increase the overall maximum results beyond 2,000 records.

The OFFSET clause allows you to skip a specified number of rows in the results, with a maximum offset of 2,000 rows.

Note: Only records accessible to the user are returned unless the user has the View All Data permission

The maximum number of distinct objects that can be returned in a single SOSL query is 20.

For each object specified in the RETURNING clause, you can retrieve a maximum of 100 fields.

The maximum length of the SOSL search string is 10,000 characters. Logical operators are ignored after 4,000 characters, so it’s important to keep search strings concise and focused.

When using SOSL with external objects, keep in mind:

  • Search Enablement: Ensure search is enabled on both the external object and its data source.
  • Searchable Fields: Only text, text area, and long text area fields are searchable.
  • Unsupported Features: External objects don’t support INCLUDES, LIKE, EXCLUDES, toLabel(), or Salesforce Knowledge-specific clauses.
  • RETURNING Clause: External objects must be explicitly listed in the RETURNING clause.
  • Text String Limit: Text strings must be 100 characters or fewer.

SOSL queries can be seamlessly integrated into Apex code using the search statement, it allows you to search across multiple objects simultaneously using full-text search capabilities.

When executed, SOSL queries return a list of lists of sObjects List<List<SObject>> where each inner list contains search results for a specific object type. The result lists are always returned in the same order as specified in the SOSL query, and if no records are found for an object type, an empty list is returned for that object

// Simple SOSL search across all fields
List<List<SObject>> searchResults = [
FIND 'Acme*' IN ALL FIELDS
RETURNING
Account(Id, Name, Industry),
Contact(Id, FirstName, LastName, Email)
];
// Cast results to specific sObject types
List<Account> accounts = (List<Account>) searchResults[0];
List<Contact> contacts = (List<Contact>) searchResults[1];

Overall, this code performs a search for records related to “Acme” across all fields in the Account and Contact objects and retrieves specific fields for each object. The second part then casts the results to lists of Account and Contact for further processing.

This Apex example demonstrates a typical workflow for using SOSL, highlighting its utility in building dynamic search functionalities within Salesforce applications.

Similarly to SOQL; SOSL supports variable binding using the colon : syntax, allowing dynamic search queries:

// Set bind variables
String term = 'Tech*';
Integer minRevenue = 1000000;
// SOSL search across name fields
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING
Account(Id, Name, AnnualRevenue WHERE AnnualRevenue > :minRevenue ORDER BY AnnualRevenue DESC LIMIT 10),
Contact(Id, FirstName, LastName, Email)
];

This code snippet searches for records with names starting with “Tech” in the Account and Contact objects. It uses bind variables to dynamically set the search term and revenue filter. For the Account object, it retrieves records with an AnnualRevenue greater than 1,000,000, orders them by revenue in descending order, and limits the results to the top 10. The Contact object results include basic fields without additional filters.

  • Bracket Notation: Enclose the entire SOSL query in square brackets
  • Return Type: The query returns List<List<SObject>>; each inner list matches one object in the RETURNING clause.
  • Variable Binding: Use :variableName to insert Apex variables into SOSL clauses (FIND, WHERE, LIMIT, etc.).
  • Casting: Cast each inner list to the specific object type.
  • Governor Limits: Up to 20 SOSL queries per Apex transaction; max 2,000 records returned across all objects.
  • Error Handling: Consider implementing error handling to manage exceptions that may arise from SOSL queries, such as handling null results or query limits being exceeded.
  • Performance Considerations: Be mindful of the performance impact of SOSL queries, especially when dealing with large datasets or complex queries. Optimize queries by limiting the number of fields and records returned.
  • Security and Permissions: Ensure that the SOSL query respects user permissions and security settings, as only records accessible to the user will be returned.
  • Testing: Thoroughly test SOSL queries in a sandbox environment to ensure they perform as expected and handle edge cases effectively.

Don’t forget when using SOSL in apex to wrap the search criteria in single quotes and not curly brackets

SOQL follows a clear, structured approach where you specify exactly what object and fields you want to query and also closely aligns with SQL so many developers find it easier to understand. SOSL has a steeper learning curve. As SOSL uses a unique ‘FIND-IN-RETURNING’ structure that differs significantly from traditional query languages, new developers often find this syntax less intuitive than SOQL’s SQL-like approach.

Choosing between SOQL (Salesforce Object Query Language) and SOSL (Salesforce Object Search Language) depends on your specific data retrieval needs, search scope, and performance requirements. Understanding when to use each language is crucial for efficient Salesforce development.

  • Structured Data Retrieval: SOQL is ideal when you know exactly which object and fields contain the data you need. It functions like a SQL SELECT statement, perfect for precise, structured queries.
  • Single or Related Object Queries: SOQL excels at retrieving data from a single object or multiple related objects with established relationships. It supports both parent-to-child and child-to-parent relationship queries using subqueries and dot notation.
  • Data Analysis and Aggregation: Use SOQL for counting records that meet specific criteria, sorting results, or retrieving data from number, date, or checkbox fields. It supports aggregate functions like COUNT(), SUM(), AVG(), MAX(), and MIN().
  • Performance-Critical Single Object Queries: SOQL is generally more efficient for targeted queries on specific objects, especially when using indexed fields for filtering.
  • Global Text-Based Searches: SOSL is perfect for searching specific terms across multiple objects simultaneously, especially when the exact object or field is unknown. It performs full-text searches against Salesforce’s search index.
  • Cross-Object Search Capability: SOSL shines when searching unrelated objects efficiently, retrieving data from multiple objects without predefined relationships.
  • Relevance-Ranked Results: SOSL returns results ranked by relevance based on search terms, making it ideal for user-facing search functionality. The search index provides faster and more relevant results for text-based queries.
  • International Language Support: Choose SOSL for data in languages like Chinese, Japanese, Korean, or Thai due to its morphological tokenization capabilities.
  • Duplicate Detection and Global Search: SOSL is effective for identifying potential duplicates across multiple objects or implementing global search features in applications.
  • SOSL Performance Advantages: Generally faster than SOQL for text searches using CONTAINS terms, with an optimized search index providing quicker results for tokenized text searches. It is more efficient when searching for specific terms across multiple objects.
  • SOQL Performance Advantages: More efficient for structured queries on single objects with known relationships, better for queries requiring complex filtering, sorting, and aggregation, and optimal when using selective filters with indexed fields.

Both languages have different governor limits that affect usage decisions. SOQL allows 100 synchronous queries per transaction and 50,000 records per query, while SOSL permits 20 queries per transaction and 2,000 total records returned across all objects. SOSL doesn’t support big objects, whereas SOQL can query them with appropriate considerations.

Choose SOQL when you know the specific object and fields to query, need complex filtering, sorting, or aggregation, are working with related objects through established relationships, performance is critical for single-object queries, or you need to retrieve large datasets (up to 50,000 records).

Choose SOSL when you need to search across multiple unrelated objects, the exact location of data is unknown, you’re implementing user-facing search functionality, you need relevance-ranked text search results, you’re working with international character sets, or you need to identify potential duplicates across the org.

The key principle is that SOQL is for structured, targeted queries when you know what you’re looking for, while SOSL is for flexible, broad searches when you’re exploring or when users need to find data across the entire organization.

Salesforce Object Search Language (SOSL) is an indispensable tool for developers and administrators needing to perform flexible, text-based searches across multiple objects in Salesforce. Its ability to search various field types, utilize wildcards and logical operators, and integrate seamlessly with Apex and other Salesforce APIs makes it highly effective for scenarios where the exact location of data is unknown or when broad search capabilities are required. By understanding SOSL’s syntax, clauses, and limitations, you can leverage its power to build robust and efficient search functionalities within your Salesforce environment, complementing the more structured querying capabilities of SOQL.