Sub topic 9
Passing values with bind variables
This chapter assumes you can write a basic FIND and RETURNING query and read the List<List<SObject>> result in Apex. It covers how to pass Apex values into static SOSL with bind variables, and where binds stop working.
What a bind variable is
A bind variable is an Apex variable that you reference inside a static SOSL query by putting a colon in front of its name. The compiler checks the query at save time. At run time, Apex substitutes the variable's value into the query.
Static SOSL sits inside square brackets. You can bind in these places:
- The search term after FIND.
- Values in a per-object WHERE filter.
- The number in LIMIT or OFFSET.
String term = 'Acme';
String industry = 'Technology';
Integer maxRows = 10;
List<List<SObject>> results = [
FIND :term IN ALL FIELDS
RETURNING
Account(Id, Name WHERE Industry = :industry ORDER BY Name LIMIT :maxRows),
Contact(Id, Name WHERE Email != null)
];
List<Account> accounts = (List<Account>) results[0];Each value has its own variable. :term supplies the search text, :industry filters Account only, and :maxRows caps the Account list. The Contact list is not affected by any of them.
Why binds are safer than concatenation
When you bind a value, Apex treats it as data and not as query text. A user who types Acme' RETURNING User(Id) cannot add a new clause, because the whole string is searched as a term. You do not need String.escapeSingleQuotes for a bound value.
Concatenation has no such protection. Building the query as a string and running it with Search.query makes you responsible for escaping. The next chapter covers that case. Prefer a bind whenever the query shape is fixed.
Binding wildcards and phrases
A bound term is still parsed as a search expression. Wildcards such as * and ? keep their meaning inside the value. To search for names that start with the user's text, add the wildcard to the variable:
public with sharing class ContactLookup {
public static List<Contact> byPrefix(String userInput) {
String term = userInput + '*';
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING Contact(Id, FirstName, LastName LIMIT 20)
];
return (List<Contact>) results[0];
}
}Keep two points in mind:
- A search term needs at least two characters besides wildcards. An empty or one-letter value throws a
SearchException, so check the input length first. - If the user's text contains search operators such as
AND,OR, or quotation marks, the search engine reads them as operators. Binding prevents injection into the query structure. It does not stop users from changing the meaning of the search term.
Binding collections
In a WHERE filter, a bound List or Set works with IN. This applies the same way as in SOQL.
Set<String> types = new Set<String>{ 'Customer - Direct', 'Customer - Channel' };
String term = 'Global*';
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING Account(Id, Name, Type WHERE Type IN :types)
];Where binds do not work
Bind variables supply values only. You cannot bind:
- An object name in RETURNING.
- A field list.
- The search group, such as
NAME FIELDS. - A clause keyword such as
ORDER BY.
If any of these must vary, build the string and run it with Search.query. A common middle path is to keep the structure static and choose between several fixed queries with an if statement.
Common errors
| Symptom | Likely cause |
|---|---|
| `SearchException` about the search term | Bound value is null, empty, or too short |
| Compile error on a bind | The variable is not in scope, or you used it where only keywords are allowed |
| Fewer results than expected | The wildcard is missing from the variable, or the per-object WHERE filters out records |
| Unexpected matches | User text contains `AND`, `OR`, or quotes that the search engine parses as operators |
Exercise
A method receives String name from a user and runs [FIND :name IN NAME FIELDS RETURNING Account(Id, Name)]. Give two reasons the query might throw an exception, and say how to avoid each.
Show answer
The value can be null, or it can be shorter than two characters once wildcards are excluded. Both raise a SearchException. Check that the string is not blank and has at least two characters before running the query, and return an empty list otherwise.
Exercise
You want one method that searches Account or Contact depending on a parameter. Can you bind the object name? What are your options?
Show answer
No. Bind variables supply values only, so an object name in RETURNING cannot be bound. Either write two static queries and pick one with an if statement, or build a string and run it with Search.query, escaping the user's text.