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);
This is Module 20's dynamic SOQL idea (Database.query()), applied to search: Search.query() runs a SOSL search built as a String at runtime — 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)
];
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.
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)'
SOSL in Apex Quiz
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.