Sub topic 14
Dynamic SOQL and preventing injection
This chapter assumes you can write inline SOQL with bind variables and that you know how user mode works. Dynamic SOQL builds the query as a string at runtime and runs it with Database.query. Use it when the object, fields, or filters are not known until the code runs. If the query shape is fixed, use inline SOQL, because the compiler checks it for you.
Why injection happens
SOQL injection happens when untrusted input is concatenated into a query string and changes what the query means. Suppose a user types ' OR Name != ' into a search box. A concatenated query then returns every account. Inline queries are safe from this because bind variables are never parsed as query text. Dynamic queries are only at risk when you build the string yourself.
Bind variables in dynamic queries
A dynamic query string can still contain :name. Database.query resolves the bind from variables in the current scope. Database.queryWithBinds takes an explicit map, so the query does not depend on local variable names. It also takes an access level.
String name = 'Acme';
// Bind variable in a dynamic query string
String soql = 'SELECT Id, Name FROM Account WHERE Name = :name';
List<Account> viaBind = Database.query(soql);
// Explicit bind map and user mode
List<Account> viaMap = Database.queryWithBinds(
soql,
new Map<String, Object>{ 'name' => name },
AccessLevel.USER_MODE
);Prefer queryWithBinds. The binds are visible at the call site, and AccessLevel.USER_MODE enforces the running user's sharing, object permissions, and field-level security.
Escaping when you must concatenate
Sometimes a value cannot be bound. In that case, pass it through String.escapeSingleQuotes first. The method adds a backslash before each single quote, so the quote stays part of the string literal.
String risky = 'O\'Brien';
String safe = String.escapeSingleQuotes(risky);
String soql2 = 'SELECT Id FROM Contact WHERE LastName = \'' + safe + '\'';
List<Contact> contacts = Database.query(soql2);Escaping is the fallback. It protects string literals only, and it is easy to forget on one code path. Binding removes the problem.
Dynamic field and object names
Identifiers cannot be bound, so validate them against an allow-list. Never pass a user-supplied field name straight into the query.
Set<String> allowedFields = new Set<String>{ 'Name', 'Industry', 'Type' };
String sortField = 'Industry'; // imagine this arrives from a UI
if (!allowedFields.contains(sortField)) {
sortField = 'Name';
}
String soql = 'SELECT Id, Name FROM Account ORDER BY ' + sortField + ' LIMIT 50';
List<Account> accts = Database.query(soql, AccessLevel.USER_MODE);Another option is to check names against schema describe results, such as Schema.SObjectType.Account.fields.getMap(). An allow-list is simpler and also limits which fields users may choose.
Common errors
- Concatenating a value that could be bound. Replace it with
:variable. - Binding a variable that is out of scope.
Database.queryfails at runtime, not at compile time. A typo in the string is not caught until the code runs. - Trusting
escapeSingleQuotesfor field names. It does nothing useful for identifiers. - Omitting the access level. Without
AccessLevel.USER_MODE, the query runs in system mode and ignores field-level security. - Skipping tests. The compiler does not check dynamic strings, so test every branch that builds one.
Exercise
A method receives a user-supplied industry string and a user-supplied sortField string. How do you build a safe dynamic query for accounts?
Show answer
Bind industry with :industry and pass it in a map to Database.queryWithBinds. Validate sortField against an allow-list of field names, because identifiers cannot be bound. Run the query with AccessLevel.USER_MODE so sharing and field-level security apply.