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, and that you know basic Apex classes, strings and collections. It covers how Apex runs a query that you build as a string, and the errors that come with it.
Static and dynamic queries at run time
A static query is written inline in square brackets. The compiler parses it when you save the class. A dynamic query is a String that Apex parses only when the code runs. Two methods in the Database class execute that string:
| Method | Returns | Use it for |
|---|---|---|
| `Database.query(String)` | `List<SObject>` | Fetching records |
| `Database.countQuery(String)` | `Integer` | Counting records with `SELECT COUNT()` |
Fetching records with Database.query
Database.query returns a List<SObject>. Assigning it to a typed list such as List<Account> works without a cast.
public with sharing class DynamicAccountQuery {
public static List<Account> byIndustry(String industry) {
String soql = 'SELECT Id, Name FROM Account WHERE Industry = :industry LIMIT 50';
return Database.query(soql);
}
}The :industry part is a bind variable. Apex reads it from the local scope of the method that calls Database.query. Here that is the method parameter. Later chapters explain why this matters for security. For now, notice that the value never becomes part of the query text.
Counting records with Database.countQuery
Database.countQuery expects a query of the form SELECT COUNT() FROM ... and returns an Integer.
public static Integer countByIndustry(String industry) {
return Database.countQuery('SELECT COUNT() FROM Account WHERE Industry = :industry');
}Do not pass SELECT COUNT(Id) or any aggregate with a field. Those forms return AggregateResult rows, so use Database.query for them and read the result from the rows.
Building a query from optional filters
The main reason to use dynamic SOQL is a search where the filters depend on what the user supplied. Collect the clauses in a list and join them.
public static List<Account> search(String industry, Integer minEmployees) {
List<String> clauses = new List<String>();
if (String.isNotBlank(industry)) {
clauses.add('Industry = :industry');
}
if (minEmployees != null) {
clauses.add('NumberOfEmployees >= :minEmployees');
}
String soql = 'SELECT Id, Name FROM Account';
if (!clauses.isEmpty()) {
soql += ' WHERE ' + String.join(clauses, ' AND ');
}
soql += ' ORDER BY Name LIMIT 100';
return Database.query(soql);
}Only fixed text is added to the string. The user's values stay in the variables industry and minEmployees.
Common errors
Dynamic queries move many mistakes from compile time to run time.
QueryExceptionfor bad syntax or unknown names. A misspelled field, a missing space between clauses, or an unclosed quote fails only when the line runs. A test that never reaches that branch will not catch it. Print the query string while debugging.- Bind variable not found. The name after the colon must be a local variable or parameter in the calling method. Dynamic SOQL cannot read a field of an object, so
:acc.Namefails. Copy the value into a local variable first. SELECT COUNT()withDatabase.query. The result is a list with no rows, and the count is inLimits-style metadata you cannot read that way. UseDatabase.countQueryfor a plain count.- Single-record assignment.
Account a = (Account) Database.query(...)throws aQueryExceptionwhen the list is empty. CheckisEmpty()first, or take the first element only after you confirm it exists. - Missing spaces.
'... FROM Account' + 'WHERE ...'producesAccountWHERE. Start each appended piece with a space.
You can catch the exception when the query shape depends on outside input.
try {
List<Account> rows = Database.query(soql);
} catch (QueryException e) {
System.debug(LoggingLevel.ERROR, 'Bad query: ' + soql + ' -> ' + e.getMessage());
throw e;
}Limits and security mode
Dynamic queries count against the same governor limits as static ones: 100 synchronous SOQL queries per transaction and 50,000 returned rows. A query string can be at most 100,000 characters.
Database.query(String) follows the sharing of the class that calls it. It does not enforce field-level security or object permissions by default. An overload, Database.query(String, AccessLevel), can run the query in user mode. A later chapter covers it.
Exercise
A method builds the string 'SELECT COUNT(Id) FROM Contact WHERE AccountId = :accId' and passes it to Database.countQuery. What is wrong, and how do you fix it?
Show answer
Database.countQuery needs the plain form SELECT COUNT(). Change the string to 'SELECT COUNT() FROM Contact WHERE AccountId = :accId'. The bind variable accId must also be a local variable or parameter in the same method.
Exercise
Why can a dynamic query with a misspelled field name pass your deployment but fail in production?
Show answer
Apex parses a dynamic query string only when it runs, so the compiler cannot check it. The QueryException appears when that code path executes. A test that runs the path catches it.