Sub topic 7
Dynamic SOQL in user mode
This chapter assumes you can write static SOQL with WITH USER_MODE and that you know the difference between sharing and CRUD/FLS from earlier chapters. You should also be comfortable with Map, Set, and Schema describe calls.
Why dynamic queries need their own treatment
Dynamic SOQL builds a query as a String and runs it at runtime. You use it when the object, the field list, the filters, or the sort order are not known at compile time. Typical cases are a configurable search screen, a generic table component, or a service that takes field names from metadata.
Dynamic SOQL has two risks that static SOQL does not.
- Permission bypass.
Database.query(String)runs in system mode, like any other Apex code. Awith sharingclass still enforces sharing rules, but not object permissions or field-level security (FLS). - SOQL injection. If you concatenate untrusted input into the string, a caller can change the meaning of the query.
User mode addresses the first risk. Bind variables address the second. In most cases you need both.
Two ways to get user mode
You can request user mode in the query text, or you can pass an access level to the method that runs the query.
Put WITH USER_MODE in the string
The clause works the same way as in static SOQL:
String soql = 'SELECT Id, Name FROM Account WITH USER_MODE LIMIT 10';
List<Account> accounts = Database.query(soql);This works, but the security decision is buried inside a string. A reviewer, or a static analysis tool, has to read the text to find it. If someone edits the string and drops the clause, nothing fails.
Pass AccessLevel.USER_MODE to the method
The Database query methods have overloads that take an AccessLevel. The access level is a separate argument, so it is easy to see and hard to remove by accident.
List<Account> accounts = (List<Account>) Database.query(
'SELECT Id, Name FROM Account LIMIT 10',
AccessLevel.USER_MODE
);Prefer this form. AccessLevel.SYSTEM_MODE is the other value. Passing it explicitly documents that the code is deliberately running in system mode, which a later chapter covers.
Bind variables with queryWithBinds
Database.query resolves :name bind variables from local variables in scope. That works, but it ties the query string to the surrounding code. It also fails quietly if you move the query into a helper method.
Database.queryWithBinds takes the values as a Map<String, Object>. The query never has to look at local variables:
public with sharing class SafeQuery {
public static List<Account> findByIndustry(String industry) {
Map<String, Object> binds = new Map<String, Object>{ 'industry' => industry };
String soql = 'SELECT Id, Name FROM Account WHERE Industry = :industry';
return Database.queryWithBinds(soql, binds, AccessLevel.USER_MODE);
}
}The value of industry is sent as data. If it contains ' OR Name != ', that text is compared literally against the Industry field. It never becomes part of the query syntax.
Bind values can also be collections and numbers:
- A
ListorSetworks withIN :ids. - An
Integerworks withLIMIT :maxRows. - A
DateorDatetimeworks in comparisons.
The variants
Each query-running method has a "WithBinds" version and an AccessLevel overload.
| Method | Returns | Use it for |
|---|---|---|
| `Database.query(soql, accessLevel)` | `List<SObject>` | Dynamic queries with binds from local variables |
| `Database.queryWithBinds(soql, binds, accessLevel)` | `List<SObject>` | Dynamic queries with an explicit bind map |
| `Database.countQuery(soql, accessLevel)` | `Integer` | `SELECT COUNT() FROM ...` |
| `Database.countQueryWithBinds(soql, binds, accessLevel)` | `Integer` | Counts with an explicit bind map |
| `Database.getQueryLocator(soql, accessLevel)` | `Database.QueryLocator` | Batch `start` methods and large result sets |
| `Database.getQueryLocatorWithBinds(soql, binds, accessLevel)` | `Database.QueryLocator` | Batch `start` with an explicit bind map |
The WithBinds methods are the best default for new code.
What can and cannot be bound
Bind variables replace values only. You cannot bind any of these:
- an object name
- a field name
- a relationship name
- a sort field in
ORDER BY - a sort direction
If any of these come from a caller, you must validate them yourself. String.escapeSingleQuotes is not enough for an identifier. It only escapes quote characters, and an identifier does not need quotes to cause harm.
The safe approach is an allow-list. Map each permitted input to the API name you control, and ignore everything else.
public with sharing class AccountSearch {
private static final Map<String, String> SORT_FIELDS = new Map<String, String>{
'name' => 'Name',
'industry' => 'Industry',
'annualrevenue' => 'AnnualRevenue'
};
public static List<Account> search(String industry, String sortField, Boolean descending, Integer maxRows) {
String orderBy = 'Name';
if (sortField != null && SORT_FIELDS.containsKey(sortField.toLowerCase())) {
orderBy = SORT_FIELDS.get(sortField.toLowerCase());
}
String direction = (descending == true) ? 'DESC' : 'ASC';
Integer rowLimit = (maxRows == null || maxRows < 1 || maxRows > 200) ? 50 : maxRows;
Map<String, Object> binds = new Map<String, Object>{
'industry' => industry,
'rowLimit' => rowLimit
};
String soql = 'SELECT Id, Name, Industry, AnnualRevenue FROM Account '
+ 'WHERE Industry = :industry '
+ 'ORDER BY ' + orderBy + ' ' + direction + ' '
+ 'LIMIT :rowLimit';
return Database.queryWithBinds(soql, binds, AccessLevel.USER_MODE);
}
}Every piece of text that reaches the query string is either a literal in the class or a value looked up from the allow-list. The direction is reduced to one of two constants. The industry and the row limit travel as binds.
What user mode checks in a dynamic query
When you pass AccessLevel.USER_MODE, the platform checks the query as it runs. The checks cover:
- Read access to the object in
FROM. - Read access to every field in
SELECT. - Read access to fields used in
WHEREandORDER BY. - Read access to fields reached through relationships, such as
Account.Owner.Name. - Sharing rules for the running user, even when the class is declared
without sharing.
The same rules apply to static WITH USER_MODE, so a dynamic query that names a field the user cannot read fails in the same way. It does not return the record with that field blanked out. This is the main difference from Security.stripInaccessible, which removes fields silently.
The failure is a QueryException. In a dynamic query it can occur far from the code that chose the field, because the field name may come from configuration. Catch it where you can give the caller something useful.
public with sharing class DynamicReader {
public static List<SObject> readFields(List<String> fieldNames) {
Set<String> accountFields = Schema.SObjectType.Account.fields.getMap().keySet();
List<String> validated = new List<String>();
for (String name : fieldNames) {
if (accountFields.contains(name.toLowerCase())) {
validated.add(name.toLowerCase());
}
}
if (validated.isEmpty()) {
throw new IllegalArgumentException('No valid Account fields requested.');
}
String soql = 'SELECT ' + String.join(validated, ', ') + ' FROM Account LIMIT 50';
try {
return Database.query(soql, AccessLevel.USER_MODE);
} catch (QueryException e) {
System.debug(LoggingLevel.WARN, 'Dynamic read denied: ' + e.getMessage());
throw new AuraHandledException('You do not have access to one of the requested fields.');
}
}
}The describe call in this example is a validation step, not a security step. It confirms that each name is a real Account field, which keeps unexpected text out of the query. User mode does the permission check. This is the reverse of the older pattern, where isAccessible() checks were the permission check.
Reusing one dynamic query in a batch job
Database.getQueryLocatorWithBinds lets a batch class use user mode in start:
public with sharing class EnergyAccountBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
Map<String, Object> binds = new Map<String, Object>{ 'industry' => 'Energy' };
return Database.getQueryLocatorWithBinds(
'SELECT Id, Name FROM Account WHERE Industry = :industry',
binds,
AccessLevel.USER_MODE
);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
// Process the records. Use `as user` or an AccessLevel on DML if the writes must respect permissions.
}
public void finish(Database.BatchableContext bc) {}
}The access level on the locator covers only the query. Any DML in execute needs its own user mode, which the next chapters on DML and the Database methods describe.
Choosing between the forms
The decision is short.
Common mistakes
- Concatenating values into the string.
'... WHERE Industry = \'' + industry + '\''reintroduces injection. Bind the value instead. - Forgetting the access level.
Database.query(soql)with no second argument runs in system mode. The method name looks the same, and the code compiles. - Believing
with sharingcovers FLS. The keyword enforces record sharing only. Awith sharingclass that callsDatabase.query(soql)still reads fields the user cannot see. - Treating describe validation as authorization. A field existing in the schema says nothing about whether this user can read it.
- Mixing a bind name and a map key. A
:industryplaceholder with noindustrykey in the map raises an error at runtime, not at compile time. Test each dynamic path. - Using the local-variable form in a helper.
Database.querywith binds depends on variables visible where the call is made. Move the query and it breaks, or binds the wrong value.
Testing a dynamic query
Apex tests run in system mode by default. A test that calls your dynamic method as the test user proves nothing about permissions. Use System.runAs with a user whose profile or permission sets lack access, and assert that a QueryException is thrown or that your wrapper converts it. The chapter on testing with System.runAs shows the full setup. Also write a case where the caller supplies a sort field that is not on the allow-list, and assert that the default order is used.
Exercise
A method builds String soql = 'SELECT Id, Name FROM Account WHERE Name = \'' + searchTerm + '\''; and runs it with Database.query(soql, AccessLevel.USER_MODE). User mode is enabled. Is the method safe? If not, rewrite the call.
Show answer
No. User mode enforces object permissions, FLS, and sharing, but the string concatenation still allows SOQL injection. A searchTerm such as x' OR Name != 'y changes the query logic, so the caller could read any Account records the user may see, not only the ones the method meant to return. Bind the value instead:
Map<String, Object> binds = new Map<String, Object>{ 'searchTerm' => searchTerm };
List<Account> accounts = Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Name = :searchTerm',
binds,
AccessLevel.USER_MODE
);
Exercise
A caller passes the sort field name as a String. Why can't you pass it as a bind variable, and what should you do instead?
Show answer
Bind variables replace values only, so they cannot stand in for field names, object names, or ORDER BY identifiers. Keep an allow-list (for example a Map from lowercase input to the real API name), look up the caller's value in it, and fall back to a default when it is not found. Only the looked-up value is concatenated into the query string.
Exercise
A dynamic query in user mode lists the field AnnualRevenue. The running user cannot read that field. What happens, and how does this differ from Security.stripInaccessible?
Show answer
The query throws a QueryException, so no records are returned. Catch it and return a clear message. Security.stripInaccessible, by contrast, removes inaccessible fields from the records and does not throw, so the caller gets partial data.