Using Apex Variables in SOQL and SOSL Queries
SOQL and SOSL statements in Apex can reference Apex code variables and expressions if they’re preceded by a colon (:). This use of a local code variable within a SOQL or SOSL statement is called a bind. The Apex parser first evaluates the local variable in code context before executing the SOQL or SOSL statement. Bind expressions can be used as:
- The search string in
FINDclauses. - The filter literals in
WHEREclauses. - The value of the
INorNOT INoperator inWHEREclauses, allowing filtering on a dynamic set of values. Note that this is of particular use with a list of IDs or Strings, though it works with lists of any type. - The division names in
WITH DIVISIONclauses. - The numeric value in
LIMITclauses. - The numeric value in
OFFSETclauses.
For example:
Apex bind variables aren’t supported for the units parameter in the DISTANCE function. This query doesn’t work.