Sub topic 3
Passing Values with Bind Variables
Assume you know basic SOQL, Apex variables, collections, and loops. This chapter focuses on values that change at runtime, safe query construction, and testing.
Bind variables in static SOSL
A bind variable inserts an Apex variable into a static SOSL query. Static SOSL is checked by Salesforce when Apex is compiled, so it is usually safer and easier to maintain than a string-built query.
String term = 'Acme';
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING Account(Id, Name LIMIT 10)
];
List<Account> accounts = (List<Account>) results[0];The colon before term marks it as a bind variable. The result is still a list for each object in the RETURNING clause.
Dynamic SOSL with Search.query
Use Search.query when the query structure must change at runtime. Escape user input before adding it to the SOSL string.
public with sharing class AccountSearch {
public static List<Account> findAccounts(String userInput) {
String safe = String.escapeSingleQuotes(userInput);
String query =
'FIND \'' + safe +
'\' IN NAME FIELDS RETURNING Account(Id, Name LIMIT 20)';
List<List<SObject>> results = Search.query(query);
return (List<Account>) results[0];
}
}Escaping prevents an apostrophe in the input from changing the query text. Prefer static SOSL with bind variables whenever the structure is fixed.
Limits, sharing, and field access
SOSL consumes governor limits, which restrict resource use per transaction. Keep searches narrow with RETURNING, WHERE, and LIMIT. A with sharing class respects record-sharing rules. Field-level security still matters: expose only fields the running user can access, especially in controller or API code.
Testing SOSL code
New test records are not reliably searchable immediately. Test.setFixedSearchResults makes the test return selected record IDs.
Test.setFixedSearchResults(new List<Id>{ acc.Id });
Test.startTest();
List<Account> found = AccountSearch.findAccounts('Acme');
Test.stopTest();
System.assertEquals(1, found.size());Refinements and REST
SOSL also supports optional WITH refinements, such as HIGHLIGHT and SNIPPET, when the client needs search context. These features add response detail but do not replace RETURNING filters.
The REST API accepts SOSL through the search resource. Send a URL-encoded query, authenticate the request, and inspect the returned object result groups. Apply the same input validation and least-data principles as in Apex.
Exercise
When should you use a bind variable instead of Search.query?
Show answer
Use a bind variable when the SOSL structure is fixed and only a value changes. Use Search.query when trusted code must build the query structure at runtime.