Sub topic 2
Running dynamic queries with Database.query and Database.countQuery
This chapter assumes you can write static SOQL with WHERE, ORDER BY and LIMIT. It also assumes you know Apex classes, collections and sObjects, and that you know sharing and field-level security (FLS) exist. It covers how the two core dynamic query methods behave: what they return, how they resolve variables, how they fail, and which limits apply. The earlier chapter explained why you sometimes need a query built at run time. The next chapters explain how attackers abuse these methods and how to defend against that.
What Database.query does
Database.query(String) takes a SOQL string and runs it. The platform parses the string when the line executes, not when the class is saved. A static query is checked at compile time, so a typo in a field name stops the save. A dynamic query compiles with any text, and mistakes only show up as exceptions at run time.
public with sharing class AccountQueryService {
public static List<Account> findByIndustry(String industry) {
String soql = 'SELECT Id, Name, Industry FROM Account WHERE Industry = :industry LIMIT 100';
return Database.query(soql);
}
}The method returns List<SObject>. Apex lets you assign it to a List<Account> directly, and it throws a System.TypeException if the query selects from a different object. The results are real Account records, so you can read fields, update them and pass them to other methods as usual.
The table compares the methods in this family.
| Method | Returns | Typical use |
|---|---|---|
| `Database.query(String)` | `List<SObject>` | Fetch records from a query built at run time |
| `Database.countQuery(String)` | `Integer` | Count matching records without loading them |
| `Database.queryWithBinds(String, Map, AccessLevel)` | `List<SObject>` | Pass bind values in a map, with an explicit access level (covered later) |
| `Database.getQueryLocator(String)` | `Database.QueryLocator` | Feed a batch job or a Visualforce controller |
Return types and assignment
The shape of the result depends on the query. Three cases come up often.
- A normal
SELECTreturns a list, which can be empty. An empty list is not an error. - An aggregate query such as
GROUP BYreturnsList<AggregateResult>. - Assigning the result to a single record, such as
Account a = Database.query(...), works only when exactly one row comes back. Zero rows or several rows throw aQueryException.
public with sharing class SingleAccountLookup {
public static Account byId(Id accountId) {
List<Account> rows = Database.query('SELECT Id, Name FROM Account WHERE Id = :accountId LIMIT 1');
return rows.isEmpty() ? null : rows[0];
}
}Assigning to a list and checking isEmpty() is safer than assigning to a single record. It also lets you decide what "not found" means, instead of letting a platform exception decide.
A second gotcha is fields you did not select. If the string says SELECT Id, Name and your code reads acc.Industry, Apex throws a System.SObjectException saying the field was not queried. In a dynamic query the field list is a string, so no compiler warns you.
Bind variables resolve from local scope
A colon followed by a name, such as :industry, is a bind variable. Apex looks the name up in the scope where Database.query is called, so the variable must be a local variable or a parameter of that method.
Three rules keep this predictable:
- The variable must be visible at the line that calls
Database.query. A variable that exists only in another method is not found. - You can bind a simple variable, such as a
String,Id,DateorList<Id>. You cannot bind a field of an object, such as:acc.Name. Copy the value into a local variable first. - A bind name that has no matching variable causes a
QueryExceptionat run time, not a compile error.
public with sharing class ContactsForAccounts {
public static List<Contact> forAccounts(Set<Id> accountIds) {
// Binding a collection works with IN.
return Database.query('SELECT Id, LastName, AccountId FROM Contact WHERE AccountId IN :accountIds');
}
}Bind variables are also the main defense against SOQL injection, because a bound value is never parsed as query text. A later chapter develops that point. For now, treat them as the normal way to put a value into a dynamic query.
Building a query with optional filters
The most common reason to use dynamic SOQL is a search form where users fill in some filters and leave others blank. You assemble the WHERE clause from fixed fragments and bind the values.
public with sharing class OpportunitySearch {
public static List<Opportunity> search(String stage, Decimal minAmount) {
List<String> conditions = new List<String>();
if (String.isNotBlank(stage)) {
conditions.add('StageName = :stage');
}
if (minAmount != null) {
conditions.add('Amount >= :minAmount');
}
String soql = 'SELECT Id, Name, StageName, Amount FROM Opportunity';
if (!conditions.isEmpty()) {
soql += ' WHERE ' + String.join(conditions, ' AND ');
}
soql += ' ORDER BY CloseDate DESC LIMIT 200';
return Database.query(soql);
}
}Every string added to conditions is a literal written by the developer. The user's text never enters the query string. The stage and minAmount parameters are in scope at the Database.query call, so the binds resolve. A bind variable that is not used because its filter was skipped is harmless.
Two habits make this pattern easier to maintain:
- Always end with a
LIMIT, so a search with no filters cannot try to read the whole table. - Log or inspect the final string while developing.
System.debug(soql)shows exactly what the platform will parse.
Counting with Database.countQuery
Database.countQuery(String) returns an Integer. Use it when you need only the number of matching records, for example to show "1,240 results" or to compute the number of pages. It avoids loading records into the heap.
public with sharing class OpportunityCounter {
public static Integer countByStage(String stage) {
String soql = 'SELECT COUNT() FROM Opportunity WHERE StageName = :stage';
return Database.countQuery(soql);
}
}The query must use the SELECT COUNT() form with no field inside the parentheses. A query that selects fields, or one that uses COUNT(Id), is not what countQuery expects, and it fails with a QueryException. If you need grouped counts, use Database.query instead, as shown in the next section.
A typical pagination service runs the count and the page query from the same filter. Build the WHERE clause once and reuse it, so the two queries cannot drift apart.
public with sharing class OpportunityPager {
public class Page {
public Integer total;
public List<Opportunity> rows;
}
public static Page load(String stage, Integer pageSize, Integer pageNumber) {
Integer size = Math.min(Math.max(pageSize == null ? 25 : pageSize, 1), 200);
Integer offsetRows = Math.max((pageNumber == null ? 1 : pageNumber) - 1, 0) * size;
String whereClause = String.isNotBlank(stage) ? ' WHERE StageName = :stage' : '';
Page result = new Page();
result.total = Database.countQuery('SELECT COUNT() FROM Opportunity' + whereClause);
result.rows = Database.query(
'SELECT Id, Name, StageName FROM Opportunity' + whereClause +
' ORDER BY Name LIMIT :size OFFSET :offsetRows'
);
return result;
}
}Here size and offsetRows are Integer values computed in code, and they are bound as well. Limiting the page size to 1 through 200 keeps a caller from asking for an unbounded page. Note that OFFSET has its own maximum of 2,000 rows, so deep paging needs a different strategy.
Aggregate queries and other query shapes
Database.query handles any valid SOQL, including aggregates. The result is a list of AggregateResult rows, and you read each value by alias with get.
public with sharing class AccountStats {
public static Map<String, Integer> countByIndustry() {
Map<String, Integer> result = new Map<String, Integer>();
List<AggregateResult> rows = Database.query(
'SELECT Industry ind, COUNT(Id) cnt FROM Account WHERE Industry != null GROUP BY Industry'
);
for (AggregateResult ar : rows) {
result.put((String) ar.get('ind'), (Integer) ar.get('cnt'));
}
return result;
}
}You can also loop over the result directly with for (Account a : Database.query(soql)). A dynamic SOQL for loop is processed in chunks and uses less heap than first storing a full list. For batch Apex, Database.getQueryLocator(soql) accepts the same string and lets the platform read up to 50 million records.
Runtime errors you will see
Because the platform parses the string at run time, errors move from the compiler to your users. Catch QueryException where the query is run, and decide what to tell the caller.
public with sharing class SafeAccountSearch {
public class SearchException extends Exception {}
public static List<Account> byRating(String rating) {
try {
return Database.query('SELECT Id, Name, Rating FROM Account WHERE Rating = :rating LIMIT 50');
} catch (QueryException e) {
System.debug(LoggingLevel.ERROR, 'Account search failed: ' + e.getMessage());
throw new SearchException('The search could not be completed.');
}
}
}The table lists the usual causes.
| Symptom | Cause |
|---|---|
| `QueryException`: unexpected token or syntax error | A missing space, comma or quote when joining fragments |
| `QueryException`: no such column | A misspelled field, or a field the user cannot read (for example when running in user mode) |
| `QueryException`: variable does not exist | The bind name is not in scope where `Database.query` runs |
| `QueryException`: list has no rows for assignment | The result was assigned to a single record and zero rows came back |
| `SObjectException`: field was not queried | The code reads a field that is missing from the `SELECT` list |
The message you log should help developers, but the message you show users should not. Raw platform messages can reveal object and field names, so return a generic message to the caller.
Sharing and security defaults
A dynamic query runs with the same defaults as a static one. If the class is declared with sharing, record-level sharing applies. If it is without sharing, or inherits from a caller that is, the query sees every record. Object permissions (CRUD) and FLS are not enforced by default. By default Apex runs in system mode, so a query can return fields the current user cannot see.
You can ask for user mode, either in the query string with WITH USER_MODE or by passing an AccessLevel argument to the query method. Later chapters explain this and Database.queryWithBinds, so only the idea is introduced here.
public with sharing class UserModeExample {
public static List<Account> visibleAccounts() {
return Database.query('SELECT Id, Name FROM Account WITH USER_MODE LIMIT 50');
}
}Limits to keep in mind
- Every
Database.queryand everyDatabase.countQuerycall counts toward the SOQL queries limit, which is 100 per synchronous transaction. Running one query per record inside a loop breaks this limit quickly. - Query results count toward the 50,000-row limit for retrieved records. A
LIMITclause keeps this under control. - A SOQL statement can be at most 100,000 characters long. Long field lists or many
ORclauses can reach this. - Results held in a
Listuse heap memory. Prefer a SOQLforloop or a count when you do not need every record at once.
Exercise
A developer writes Integer n = Database.countQuery('SELECT COUNT(Id) FROM Account WHERE Industry = :ind'); inside a method that has a parameter named industry. Name two reasons this call can fail and how to fix each.
Show answer
First, the bind name :ind does not match any variable in scope, because the parameter is called industry. Rename the bind to :industry or rename the parameter, so the names are the same. This causes a QueryException at run time. Second, countQuery expects the SELECT COUNT() form, and COUNT(Id) does not fit it. Change the query to SELECT COUNT() FROM Account WHERE Industry = :industry. If a count per group is needed, use Database.query with GROUP BY and read the AggregateResult rows.
Exercise
Why is Account a = Database.query('SELECT Id FROM Account WHERE Name = :n'); risky, and what is the safer way to write it?
Show answer
Assigning the result to a single Account works only when exactly one row matches. Zero rows or two or more rows throw a QueryException. Assign the result to a List<Account>, check isEmpty(), and then decide what to do. Adding LIMIT 1 also prevents the multiple-row case, though the empty case still needs a check.