Sub topic 5
Database.queryWithBinds and the bind map
This chapter covers Database.queryWithBinds, the method that takes bind values from a map instead of from local variables. It assumes you can read and write Apex classes, static SOQL with WHERE, ORDER BY and LIMIT, and Apex collections. It also assumes you know that bind variables keep user input out of the query text. The chapter after this one covers converting input to typed values, and the one after that covers LIKE wildcards in more detail.
Why a second bind mechanism exists
In dynamic SOQL, Database.query resolves a bind variable such as :name by looking for a local variable with that name in the scope of the call. That works in a small method. It becomes fragile in three situations:
- The query string is built in one method and executed in another, so the variable is no longer in scope.
- The query text comes from a shared helper or a configuration object that has no access to the caller's variables.
- A refactor renames or removes a local variable, and the query fails only at run time because the compiler does not check names inside a string.
Database.queryWithBinds removes the dependency on scope. You pass the values explicitly in a Map<String, Object>, and the keys of the map are the bind names used in the query. Because the map is an ordinary object, it can be built, passed around, and tested separately from the query text.
The method signature
Database.queryWithBinds(String queryString, Map<String, Object> bindMap, System.AccessLevel accessLevel)The method returns a List<SObject>. You can assign the result to a typed list such as List<Account>, and Apex converts it for you.
| Parameter | Meaning |
|---|---|
| `queryString` | The SOQL text. Bind variables appear as `:name`. |
| `bindMap` | Keys are bind names without the colon. Values are the data to bind. |
| `accessLevel` | `AccessLevel.USER_MODE` or `AccessLevel.SYSTEM_MODE`. |
There is also Database.countQueryWithBinds, which has the same shape and returns an Integer. Use it where you would use Database.countQuery.
A diagram helps show where the values travel, so here is the flow.
The query text and the values travel on separate paths. User input never becomes part of the query text, which is why a quote inside the input cannot change the structure of the query.
A first example
This method searches accounts by name. The query is a constant. The only thing that varies is the value in the map.
public with sharing class AccountSearch {
public static List<Account> findByName(String name) {
Map<String, Object> binds = new Map<String, Object>{ 'name' => name };
return Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Name = :name LIMIT 50',
binds,
AccessLevel.USER_MODE
);
}
}If a caller passes ' OR Name != ', the database looks for an account whose name is exactly that string of characters. It matches nothing, because the input is a value and not part of the query.
Bind names and the map
The rules for the map are short, but each one causes real errors.
- Keys have no colon. The query uses
:name, and the map key is'name'. - Keys are matched case-insensitively. Apex is case-insensitive in general, and
'Name'and'name'refer to the same bind. Do not rely on two keys that differ only by case. - Every bind in the query needs a key. If the query mentions
:termand the map has notermkey, the call throws aQueryException. A key that is present with anullvalue is valid and bindsnull. - Extra keys are harmless. A key in the map that the query never mentions is ignored. This lets you reuse one map with several queries, but it also hides typos, so keep maps small.
- Values can be any type SOQL accepts. That includes
String,Id,Integer,Decimal,Date,Datetime,Boolean, and collections of these.
Binding collections with IN
A collection in the map works with IN and NOT IN, so you never have to build a comma-separated string yourself.
public static List<Contact> findByAccountIds(Set<Id> accountIds, List<String> titles) {
Map<String, Object> binds = new Map<String, Object>{
'accountIds' => accountIds,
'titles' => titles
};
return Database.queryWithBinds(
'SELECT Id, LastName, Title FROM Contact ' +
'WHERE AccountId IN :accountIds AND Title IN :titles',
binds,
AccessLevel.USER_MODE
);
}The concatenation here joins two fixed string literals. No input is added to the text. That is safe, and it is how you split a long query across lines.
Several binds and mixed types
One map can carry values of different types. This query filters on a date, a number, and a boolean at the same time.
public static List<Opportunity> findOpen(Date closeBefore, Decimal minAmount, Boolean isWon) {
Map<String, Object> binds = new Map<String, Object>{
'closeBefore' => closeBefore,
'minAmount' => minAmount,
'isWon' => isWon
};
return Database.queryWithBinds(
'SELECT Id, Name, Amount, CloseDate FROM Opportunity ' +
'WHERE CloseDate < :closeBefore AND Amount >= :minAmount AND IsWon = :isWon ' +
'ORDER BY CloseDate LIMIT 100',
binds,
AccessLevel.USER_MODE
);
}The method parameters are already typed, so a caller cannot smuggle text into the date or the number. If your values start as strings from a web request or a Lightning component, convert them first. That is the subject of the next chapter.
Building the map dynamically
The main reason to use a map is that you can add only the filters the user supplied. The query text still contains only fixed fragments. The map and the WHERE clause grow together.
public with sharing class OpportunityFilter {
public static List<Opportunity> search(String stageName, Decimal minAmount) {
List<String> conditions = new List<String>();
Map<String, Object> binds = new Map<String, Object>();
if (String.isNotBlank(stageName)) {
conditions.add('StageName = :stageName');
binds.put('stageName', stageName);
}
if (minAmount != null) {
conditions.add('Amount >= :minAmount');
binds.put('minAmount', minAmount);
}
String soql = 'SELECT Id, Name, StageName, Amount FROM Opportunity';
if (!conditions.isEmpty()) {
soql += ' WHERE ' + String.join(conditions, ' AND ');
}
soql += ' ORDER BY Name LIMIT 50';
return Database.queryWithBinds(soql, binds, AccessLevel.USER_MODE);
}
}Every string added to soql is a literal written by the developer: a condition, ' WHERE ', ' AND ', and the ORDER BY clause. The user's values only appear in binds. This is the pattern to look for in code review. If a variable that came from outside is concatenated into soql, the code is vulnerable, even when a map is also present.
Access level
The third argument is required, and it decides whose permissions apply.
AccessLevel.USER_MODEenforces the running user's object permissions, field-level security, and sharing rules. Inaccessible fields in the query cause an exception, and records the user cannot see are not returned.AccessLevel.SYSTEM_MODEruns without object and field permission checks. Sharing still follows the class declaration (with sharingorwithout sharing).
Choose USER_MODE unless you have a documented reason to read data the user cannot normally read. The later chapter on user mode covers the details and the exceptions you must handle.
Comparison with Database.query
| Feature | `Database.query` | `Database.queryWithBinds` |
|---|---|---|
| Where bind values come from | Local variables in scope | An explicit `Map<String, Object>` |
| Compile-time checking of names | None | None |
| Access level argument | Optional overload | Required |
| Count variant | `Database.countQuery` | `Database.countQueryWithBinds` |
| Works when query is built in another method | Only if variables are in scope | Yes |
| Resists injection when input stays out of the text | Yes | Yes |
Both methods are equally safe when you use them correctly. queryWithBinds is the better default for new code because the values and the permission level are visible at the call site.
Common errors
- Putting the colon in the key.
binds.put(':name', value)does not match:namein the query. Use'name'. - Forgetting a key. The query refers to
:term, but the map holds'Term2'. The call throws aQueryExceptionthat names the missing variable. - Binding a field name.
WHERE :fieldName = 'x'does not compare a field. SOQL treats the bind as a value, so you compare a string to a string. Field names, object names, and sort direction need an allowlist, covered in a later chapter. - Mismatched types. Binding a
Stringto aDatefield can fail or compare incorrectly. Bind aDate. - Assuming
LIKEis escaped. Binding'%' + input + '%'is safe from injection, but a%or_typed by the user still acts as a wildcard. - Large collections. A bound
INlist is still subject to SOQL limits on query length and bind size. Process very large sets in chunks.
Testing the bind map
Test the shape of the result, not only the happy path. This test checks that a filter built from the map returns the expected record and that a hostile string returns nothing.
@IsTest
private class OpportunityFilterTest {
@IsTest
static void filtersByStageAndTreatsQuotesAsText() {
insert new Opportunity(
Name = 'Renewal',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
);
List<Opportunity> found = OpportunityFilter.search('Prospecting', null);
Assert.areEqual(1, found.size(), 'The stage filter should match one record');
List<Opportunity> hostile = OpportunityFilter.search('\' OR StageName != \'', null);
Assert.areEqual(0, hostile.size(), 'A quote in the input must be treated as text');
}
}Summary
Database.queryWithBinds takes the query text, a map of bind values, and an access level. The text holds only developer-written fragments and :name placeholders. The map holds every value that came from outside. Keys have no colon, every placeholder needs a key, and collections work with IN. Field names, object names, and sort direction cannot be bound, so they need the allowlist techniques that follow.
Exercise
A developer writes String soql = 'SELECT Id FROM Account WHERE Name = :n AND Industry = \'' + industry + '\''; Database.queryWithBinds(soql, new Map<String, Object>{ 'n' => name }, AccessLevel.USER_MODE);. Is this query safe from SOQL injection? Say why, and rewrite it.
Show answer
It is not safe. The name value is bound correctly, but industry is concatenated into the query text, so a quote in industry can change the query. Passing a bind map does not protect the concatenated part. The fix is to bind both values: 'SELECT Id FROM Account WHERE Name = :n AND Industry = :industry' with the map { 'n' => name, 'industry' => industry }.
Exercise
A query uses WHERE Name = :term, and the map is new Map<String, Object>{ ':term' => 'Acme' }. What happens, and what is the correction?
Show answer
The key ':term' includes a colon, so it does not match the bind name term. The call throws a QueryException because the bind variable has no value. Use the key 'term' without the colon.