Intermediate 25 min read

SOSL in Apex

By the end of this lesson, you'll be able to:

  • Use dynamic SOSL with Search.query() when the search term isn't known at compile time
  • Apply a bind variable inside a SOSL search
  • Recognize governor limits specific to SOSL searches

Prerequisites: "Searching Multiple Objects"

Dynamic SOSL with Search.query()

String searchTerm = 'Riverbend';
String soslQuery = 'FIND {' + searchTerm + '} IN ALL FIELDS RETURNING Account(Id, Name)';

List<List<sObject>> searchResults = Search.query(soslQuery);
  1. String searchTerm = 'Riverbend'; — the search text as a variable.
  2. String soslQuery = 'FIND {' + searchTerm + '} IN ALL FIELDS RETURNING Account(Id, Name)'; — builds the whole search as a plain String at runtime.
  3. (blank line)
  4. List<List<sObject>> searchResults = Search.query(soslQuery); — this is Module 20's dynamic SOQL idea (Database.query()), applied to search — necessary when even the objects being searched aren't known until the code runs.

Bind variables in SOSL

String searchTerm = 'Riverbend';

List<List<sObject>> searchResults = [
    FIND :searchTerm IN ALL FIELDS
    RETURNING Account(Id, Name)
];
  1. String searchTerm = 'Riverbend'; — a plain Apex variable.
  2. (blank line)
  3. List<List<sObject>> searchResults = [ — opens the inline search.
  4. FIND :searchTerm IN ALL FIELDS — exactly like SOQL, an inline SOSL search accepts a bind variable with a colon prefix — the safer default over building a dynamic search string by hand, for the same SOQL-injection-style reasons covered in Module 20.
  5. RETURNING Account(Id, Name) — the object and fields to return.
  6. ]; — closes the search.

SOSL-specific governor limits

A single transaction is limited to 20 SOSL searches (compared to SOQL's separate 100-query limit), and each search returns at most 2,000 records total across every object in RETURNING. These limits exist for the same reason as every other governor limit from Module 7 and Module 18 — protecting the platform's shared, multi-tenant infrastructure — and they're worth knowing specifically because SOSL's limits are genuinely different numbers from SOQL's.

Exercise

Write dynamic SOSL using Search.query() that searches for the text stored in a variable term across Account(Id, Name).

Show hint

'FIND {' + term + '} IN ALL FIELDS RETURNING Account(Id, Name)'

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

SOSL in Apex Quiz

1. How many SOSL searches is a single transaction limited to?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

This closing lesson covers dynamic SOSL for runtime-determined searches, bind variables inside a search, and the governor limits specific to how many SOSL searches one transaction allows.