Newer Version Available
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 FIND clauses.
- The filter literals in WHERE clauses.
- The value of the IN or NOT IN operator in WHERE clauses, 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 DIVISION clauses.
- The numeric value in LIMIT clauses.
- The numeric value in OFFSET clauses.
Bind expressions can't be used with other clauses, such as INCLUDES.
For example:
1Account A = new Account(Name='xxx');
2insert A;
3Account B;
4
5// A simple bind
6B = [SELECT Id FROM Account WHERE Id = :A.Id];
7
8// A bind with arithmetic
9B = [SELECT Id FROM Account
10 WHERE Name = :('x' + 'xx')];
11
12String s = 'XXX';
13
14// A bind with expressions
15B = [SELECT Id FROM Account
16 WHERE Name = :'XXXX'.substring(0,3)];
17
18// A bind with an expression that is itself a query result
19B = [SELECT Id FROM Account
20 WHERE Name = :[SELECT Name FROM Account
21 WHERE Id = :A.Id].Name];
22
23Contact C = new Contact(LastName='xxx', AccountId=A.Id);
24insert new Contact[]{C, new Contact(LastName='yyy',
25 accountId=A.id)};
26
27// Binds in both the parent and aggregate queries
28B = [SELECT Id, (SELECT Id FROM Contacts
29 WHERE Id = :C.Id)
30 FROM Account
31 WHERE Id = :A.Id];
32
33// One contact returned
34Contact D = B.Contacts;
35
36// A limit bind
37Integer i = 1;
38B = [SELECT Id FROM Account LIMIT :i];
39
40// An OFFSET bind
41Integer offsetVal = 10;
42List<Account> offsetList = [SELECT Id FROM Account OFFSET :offsetVal];
43
44// An IN-bind with an Id list. Note that a list of sObjects
45// can also be used--the Ids of the objects are used for
46// the bind
47Contact[] cc = [SELECT Id FROM Contact LIMIT 2];
48Task[] tt = [SELECT Id FROM Task WHERE WhoId IN :cc];
49
50// An IN-bind with a String list
51String[] ss = new String[]{'a', 'b'};
52Account[] aa = [SELECT Id FROM Account
53 WHERE AccountNumber IN :ss];
54
55// A SOSL query with binds in all possible clauses
56
57String myString1 = 'aaa';
58String myString2 = 'bbb';
59Integer myInt3 = 11;
60String myString4 = 'ccc';
61Integer myInt5 = 22;
62
63List<List<SObject>> searchList = [FIND :myString1 IN ALL FIELDS
64 RETURNING
65 Account (Id, Name WHERE Name LIKE :myString2
66 LIMIT :myInt3),
67 Contact,
68 Opportunity,
69 Lead
70 WITH DIVISION =:myString4
71 LIMIT :myInt5];