Sub topic 14
Dynamic SOQL and Preventing Injection
This chapter assumes you can write inline SOQL with bind variables, read query results, and understand why queries enforce sharing and field-level security. Here you will build queries as strings at runtime and keep them safe.
Static and dynamic SOQL
Static SOQL sits in square brackets and is checked when the class compiles. Dynamic SOQL is a query held in a String and run with Database.query() or Database.queryWithBinds(). The platform parses it at runtime, so a typo in a field name becomes a runtime QueryException instead of a compile error.
Use dynamic SOQL only when the query's shape cannot be known when you write the code. Typical cases:
- The user picks which fields to show.
- The object name comes from configuration.
- Filters are added only when the user supplies a value.
If the shape is fixed, use static SOQL. It is easier to read, validates schema references at compile time, and records dependencies, so someone cannot delete a field your query uses.
Bind variables in a query string
A dynamic query string can contain bind variables with a colon, exactly like inline SOQL. Database.query() resolves them from variables in the scope where it is called.
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);The value of name is never pasted into the query text. The platform treats it as data, so quotes inside it cannot change the structure of the query.
Resolving binds from local scope has a limit. It works only when the variable is visible where Database.query() is called. If you build the string in one method and run it in another, the variable is out of scope and the query fails. Database.queryWithBinds() removes that problem by taking the values explicitly:
String name = 'Acme';
String soql = 'SELECT Id, Name FROM Account WHERE Name = :name';
List<Account> viaMap = Database.queryWithBinds(
soql,
new Map<String, Object>{ 'name' => name },
AccessLevel.USER_MODE
);Each key in the map matches a bind name in the query, without the colon. The third argument sets the access level. AccessLevel.USER_MODE enforces the running user's object permissions, field-level security, and sharing rules. AccessLevel.SYSTEM_MODE is the default behavior of Database.query() and does not enforce object or field permissions.
What SOQL injection is
SOQL injection happens when user input is concatenated into a query string and changes what the query means. Consider a search method that takes a name from a Visualforce page, a Lightning component, or a REST endpoint:
public static List<Contact> findByLastName(String input) {
String soql = 'SELECT Id, LastName FROM Contact '
+ 'WHERE LastName = \'' + input + '\'';
return Database.query(soql);
}If input is Smith, the query is correct. If input is ' OR LastName != ', the query becomes:
SELECT Id, LastName FROM Contact WHERE LastName = '' OR LastName != ''The WHERE clause is now true for nearly every row, and the method returns contacts the caller never meant to see. An attacker can also add fields, change filters, or probe which fields exist by watching which inputs cause errors. SOQL is read-only, so injection cannot delete data. It can still leak records, and it can bypass your intended filters when the code runs in system mode.
Defenses, in order of preference
- Bind variables. Values never become part of the query text. Use these whenever a value is a literal.
- Allow lists for anything that is not a value, such as field names, object names, and sort direction. Binds cannot be used for these.
String.escapeSingleQuotes()when a value must be concatenated. This is the fallback.- User mode, so that a successful injection still cannot read what the user is not allowed to see.
Escaping as a fallback
String.escapeSingleQuotes() puts a backslash before every single quote, so the quote becomes part of the string literal instead of ending it.
// If a value must be concatenated, escape it first
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 only protects values inside quotes. It does nothing for a value that is not quoted. If you concatenate a number or a field name without quotes, an attacker needs no quote character at all. Escaping is also easy to forget in one code path, while a bind variable cannot be forgotten once the pattern is in place.
Building a query from optional filters
A common dynamic query adds WHERE conditions only for inputs the user filled in. Keep the query text made of fixed fragments from your own code, and send every user value through a bind.
public with sharing class AccountSearch {
private static final Set<String> SORTABLE = new Set<String>{
'Name', 'Industry', 'AnnualRevenue'
};
public static List<Account> search(
String namePart, String industry, String sortField
) {
List<String> conditions = new List<String>();
Map<String, Object> binds = new Map<String, Object>();
if (String.isNotBlank(namePart)) {
conditions.add('Name LIKE :namePattern');
binds.put('namePattern', '%' + namePart + '%');
}
if (String.isNotBlank(industry)) {
conditions.add('Industry = :industry');
binds.put('industry', industry);
}
String soql = 'SELECT Id, Name, Industry FROM Account';
if (!conditions.isEmpty()) {
soql += ' WHERE ' + String.join(conditions, ' AND ');
}
String orderBy = SORTABLE.contains(sortField) ? sortField : 'Name';
soql += ' ORDER BY ' + orderBy + ' LIMIT 200';
return Database.queryWithBinds(soql, binds, AccessLevel.USER_MODE);
}
}Points to notice:
- The
WHEREfragments are string literals from your code. Only the bind values come from the user. - The
%wildcards are added to the bound value, not to the query text. A%or_typed by the user acts as a wildcard inside theLIKEpattern, which is usually harmless but worth knowing. sortFieldis checked against an allow list, and anything else falls back toName. The same approach works for a sort direction limited toASCandDESC.- A
LIMITkeeps the result bounded no matter what the user typed.
Validating field and object names
When the user chooses a field or object, check the name against the schema instead of trusting it. The Schema describe methods return the fields and objects that exist.
public static Boolean isQueryableField(String objectName, String fieldName) {
Schema.SObjectType type = Schema.getGlobalDescribe().get(objectName);
if (type == null) {
return false;
}
Schema.SObjectField field = type.getDescribe().fields.getMap().get(fieldName);
return field != null && field.getDescribe().isAccessible();
}This confirms the object and field exist and that the user can read the field. Describe results are case-insensitive for lookups, so 'name' and 'Name' both match. Passing the name you looked up, rather than the raw input, keeps the exact spelling under your control. Calling getGlobalDescribe() is comparatively expensive, so avoid calling it repeatedly inside a loop.
Enforcing permissions
Dynamic queries run in system mode unless you say otherwise, and with sharing on the class only controls record visibility. It does not enforce object or field permissions. There are two ways to get user-level enforcement:
| Approach | Enforces sharing | Enforces object and field security | Failure behavior |
|---|---|---|---|
| `Database.queryWithBinds(..., AccessLevel.USER_MODE)` | Yes | Yes | Throws `QueryException` if a field is inaccessible |
| `WITH USER_MODE` in the query text | Yes | Yes | Throws `QueryException` if a field is inaccessible |
| `WITH SECURITY_ENFORCED` | No, it follows the class | Yes for fields in `SELECT` | Throws `QueryException` |
| `Security.stripInaccessible()` on results | No | Yes | Removes inaccessible fields silently |
Prefer user mode in new code. It checks fields used in WHERE and ORDER BY as well as SELECT, which WITH SECURITY_ENFORCED does not. Catch the exception and show a clear message instead of letting it reach the user as a stack trace.
try {
List<Account> rows = AccountSearch.search('Acme', 'Energy', 'Name');
} catch (QueryException e) {
System.debug('Query not permitted or invalid: ' + e.getMessage());
}Common errors
- Bind variable not found.
Database.query()could not see the variable in scope. Switch toDatabase.queryWithBinds(). - Invalid field or unexpected token. A dynamic string with a typo or a stray quote. Print the final string with
System.debug(soql)while developing. - Binding a collection with
=. UseIN :idswhen the bound value is a list or set. - Unquoted values. A concatenated string value without surrounding quotes is a syntax error, and a concatenated number is an injection path.
- Query inside a loop. Dynamic queries count against the same 100 synchronous SOQL limit as static ones. Build one query and run it once.
- Testing only the happy path. Write a test that passes
' OR Name != 'and asserts that the method returns no extra rows.
@isTest
private class AccountSearchTest {
@isTest
static void injectionAttemptReturnsNothing() {
insert new Account(Name = 'Acme', Industry = 'Energy');
List<Account> result = AccountSearch.search(
'\' OR Name != \'', null, 'Name'
);
Assert.areEqual(0, result.size());
}
}The attack text is bound as a LIKE pattern, so the query looks for names containing that literal text and finds none.
Exercise
A method builds 'SELECT Id FROM Account ORDER BY ' + sortField with sortField taken from a request parameter. Why does String.escapeSingleQuotes(sortField) not make this safe, and what should you do instead?
Show answer
sortField is an identifier, not a quoted string value. An attacker can supply a harmless-looking column name that is not allowed, or other query text, and no single quote is needed, so escaping changes nothing. Compare sortField to an allow list such as a Set<String> of permitted fields, and fall back to a default like Name when it is not in the set. Also run the query with AccessLevel.USER_MODE.
Exercise
Why is Database.queryWithBinds() often a better choice than Database.query() for a query with bind variables?
Show answer
It takes the bind values as an explicit map, so the query string can be built in one method and run in another without the variables needing to be in scope. It also accepts an AccessLevel argument, so you can enforce user mode in the same call.