Sub topic 5
Database.queryWithBinds and the bind map
This chapter assumes you can write Apex classes and static SOQL, and that you know the difference between static and dynamic SOQL. You should also know why concatenating user input into a query string is dangerous. Here you learn how Database.queryWithBinds takes its values from a map instead of from local variables.
Why a bind map exists
Database.query resolves bind variables such as :name by looking at variables in the current scope. That works, but the query string depends on a local variable having the right name. If you refactor the code, or build the query in one method and run it in another, the binding can break or point at the wrong variable.
Database.queryWithBinds removes that dependency. You pass the values in a Map<String, Object>, and each :name in the query is matched to the map key with the same name. The values travel separately from the query text, so quotes in the input cannot change the query structure.
The method signature
Database.queryWithBinds(String query, Map<String, Object> bindMap, AccessLevel accessLevel)queryis the SOQL string, with:keyplaceholders.bindMapholds one entry for each placeholder.accessLevelisAccessLevel.USER_MODEorAccessLevel.SYSTEM_MODE. The third argument is required.
Use AccessLevel.USER_MODE unless you have a documented reason not to. User mode enforces the running user's sharing rules, object permissions, and field-level security.
A worked example
This method searches accounts by name and by a minimum employee count. Both values come from the caller.
public with sharing class AccountSearch {
public static List<Account> search(String input, Integer minEmployees) {
String term = '%' + (input == null ? '' : input) + '%';
Map<String, Object> binds = new Map<String, Object>{
'term' => term,
'minEmployees' => minEmployees == null ? 0 : minEmployees
};
return Database.queryWithBinds(
'SELECT Id, Name, NumberOfEmployees FROM Account ' +
'WHERE Name LIKE :term AND NumberOfEmployees >= :minEmployees ' +
'LIMIT 50',
binds,
AccessLevel.USER_MODE
);
}
}The query text is a constant. Only the map contains data from the caller. If input is ' OR Name != ', the database searches for accounts whose name contains that literal text.
Rules for the bind map
- Keys are the names without the colon. The placeholder
:termmatches the key'term'. - Key matching is case-insensitive in the same way Apex identifiers are, but use the exact same spelling to keep the code readable.
- Every placeholder in the query needs a key in the map. A missing key causes a runtime error.
- Extra keys that the query does not use are ignored.
- Values can be strings, numbers, dates, Booleans, Ids, and collections such as
List<String>orSet<Id>for use withIN.
A collection example:
public static List<Account> findByIndustries(Set<String> industries) {
return Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Industry IN :industries',
new Map<String, Object>{ 'industries' => industries },
AccessLevel.USER_MODE
);
}What binds cannot do
A bind variable stands in for a value. It cannot stand in for a field name, an object name, or a sort direction. This query does not work as intended:
// Wrong: the bind is treated as a value, not as a field name.
Database.queryWithBinds(
'SELECT Id FROM Account ORDER BY :sortField',
new Map<String, Object>{ 'sortField' => 'Name' },
AccessLevel.USER_MODE
);For identifiers, validate the input against a fixed allowlist and then concatenate the approved value. Later chapters cover that technique.
Common errors
- Missing key. The query uses
:termbut the map has'Term2'. Apex throws an exception when the query runs. - Binding user text to a LIKE without wildcards.
Name LIKE :termwith no%behaves like an equality check. - Assuming binds escape wildcards. A user who types
%still gets wildcard behavior inside a LIKE value. Binds protect the query structure, not the meaning of%and_. - Choosing system mode by accident. Passing
AccessLevel.SYSTEM_MODEskips field-level security and object permissions, though sharing still depends on the class declaration.
Exercise
A developer writes Database.queryWithBinds('SELECT Id FROM Contact WHERE LastName = :lastName', new Map<String, Object>{ 'name' => input }, AccessLevel.USER_MODE). What happens, and how do you fix it?
Show answer
The key name does not match the placeholder lastName, so the query fails at run time because the bind is missing. Change the map key to 'lastName', or rename the placeholder so both match.
Exercise
Why can't you pass a user-selected sort field through the bind map, and what should you do instead?
Show answer
A bind supplies a value, never part of the query structure such as a field name. Compare the input to an allowlist of permitted field names, then concatenate the approved name into the ORDER BY clause, with a safe default if it does not match.