Sub topic 1
Static vs Dynamic SOQL: When You Need a Query Built at Run Time
Most SOQL you write is fixed when you save the class. Sometimes the shape of the query depends on something only known at run time, such as which fields a user ticked or which object an admin configured. This chapter explains how static and dynamic SOQL differ, what you give up with dynamic SOQL, and how to tell when you need it. Later chapters cover the security risks of dynamic SOQL, so this one only sets the foundation.
Prerequisites
This chapter assumes you can:
- Read and write basic Apex classes and methods.
- Write static SOQL with
WHERE,ORDER BYandLIMIT. - Work with Apex strings,
List,SetandMap, and with sObjects. - Explain at a basic level that Salesforce restricts who sees which records (sharing) and which fields (field-level security).
You do not need any security background yet.
Static SOQL: the query is part of the code
Static SOQL is a query written inline in square brackets. The compiler reads it when you save the class.
public with sharing class StaticAccountQueries {
public static List<Account> byIndustry(String industry) {
return [
SELECT Id, Name, Industry
FROM Account
WHERE Industry = :industry
LIMIT 50
];
}
}The :industry part is a bind variable. Apex passes the variable's value to the query as data, not as text that gets parsed as SOQL. You will rely on this heavily in later chapters.
Static SOQL gives you several guarantees:
- Compile-time checking. A typo such as
Nmeinstead ofNamestops the save. The error appears in your editor, not in production. - Dependency tracking. Salesforce records that your class uses
Account.Industry. It will block you from deleting that field while the class references it. - Typed results. The query returns
List<Account>directly, with no casting. - Built-in injection safety. Because the structure is fixed in source code, a user cannot alter it through input.
The cost is rigidity. The object, the field list, the WHERE structure and the sort order are all decided when you write the code.
Dynamic SOQL: the query is a string
Dynamic SOQL is a query built as a String and executed with a method on the Database class.
public with sharing class DynamicAccountQueries {
public static List<Account> byIndustry(String industry) {
String soql = 'SELECT Id, Name, Industry FROM Account WHERE Industry = :industry LIMIT 50';
return Database.query(soql);
}
}This does the same work as the static version. Apex sees only a string until Database.query runs, so the checks above move to run time:
- A misspelled field is not caught when you save. It throws a
System.QueryExceptionwhen the line executes. - Salesforce cannot see that the string uses
Account.Industry. Someone can delete the field, and the class breaks only when that code path runs. - The method returns
List<SObject>. Assigning it toList<Account>works, but Apex checks the type at run time. - Any user input you place in the string becomes part of the query text. That is the root of SOQL injection.
You can see the run-time failure by running this in Anonymous Apex:
try {
Database.query('SELECT Id, Nme FROM Account');
} catch (QueryException e) {
System.debug(e.getMessage());
}The same query written in square brackets would not save. The debug output names the unknown column. Always test dynamic queries, including every branch that assembles the string.
Side-by-side comparison
| Aspect | Static SOQL | Dynamic SOQL |
|---|---|---|
| Syntax | `[SELECT ... ]` in code | `Database.query(String)` |
| Errors found | At save time | At run time |
| Field and object dependency tracking | Yes | No |
| Return type | Typed (`List<Account>`) | `List<SObject>`, assigned or cast |
| Query structure can change at run time | No | Yes |
| Injection risk from string building | None | Yes, if input is concatenated |
| Governor limits | Standard | Same limits, no extra allowance |
The last row matters. Dynamic SOQL is not cheaper or more expensive. Each call counts as one query against the per-transaction limit, and the 50,000-row limit applies in the same way.
When you actually need dynamic SOQL
Use dynamic SOQL when part of the query's structure, not just a value in it, is unknown until run time. Typical cases:
- Optional filters. A search form has ten filters and the user fills in two. The
WHEREclause must include only the conditions that apply. - User-chosen sort. The user clicks a column header to sort by it. Field names cannot be bound, so the
ORDER BYhas to be built as text. - User-chosen fields. A report-style component lets the user pick columns, or a field set defines them.
- Object chosen at run time. A generic utility, such as a record counter or a lookup component, works on whatever object it is configured with.
- Query parts stored as configuration. Custom metadata holds the object, filter and fields for each integration.
If only values change, you do not need dynamic SOQL. Use static SOQL with bind variables. This is the most common mistake: developers reach for string building to insert a value when :variable would do.
flowchart TDReplace nothing above; the actual diagram follows.
Example: optional filters with a built WHERE clause
Here the structure changes depending on which arguments are supplied. The pieces added to the string are fixed literals chosen by your code. The user's values are never placed in the string. They are referenced with bind variables.
public with sharing class OpportunitySearch {
public static List<Opportunity> search(String stageName, Decimal minAmount) {
List<String> conditions = new List<String>();
if (String.isNotBlank(stageName)) {
conditions.add('StageName = :stageName');
}
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 100';
return Database.query(soql);
}
}Points to notice:
- Every string literal appended to
soqlis written by you. This is the safe pattern: only trusted fragments go into the text. :stageNameand:minAmountrefer to local variables in scope at theDatabase.querycall. Apex looks them up by name when the query runs.- A bind variable in dynamic SOQL must be a simple variable name. An expression or field reference such as
:input.stageNameis not supported. Copy the value into a local variable first. - With no arguments the method still works and returns the 100 most recent opportunities.
Example: the object is unknown until run time
A generic utility cannot write FROM Account in advance. It must build the FROM clause from a name.
public with sharing class RecordCounter {
public static Integer countRecords(String objectApiName) {
Schema.SObjectType objectType = Schema.getGlobalDescribe().get(objectApiName);
if (objectType == null) {
throw new IllegalArgumentException('Unknown object: ' + objectApiName);
}
String safeName = objectType.getDescribe().getName();
return Database.countQuery('SELECT COUNT() FROM ' + safeName);
}
}This method does not paste objectApiName into the query. It looks the name up in the schema and uses the canonical name returned by Salesforce. Names that do not exist are rejected before any query is built. The reasons this works, and its limits, are covered in the chapters on allowlisting and Schema describe validation.
Database.countQuery runs a SELECT COUNT() query and returns an Integer. The next chapter looks at it and its siblings in detail.
Common errors with dynamic SOQL
- Unknown field at run time. Symptom:
System.QueryException: No such column. Cause: a typo, a deleted field, or a field the running user cannot access. Fix: test each branch, and validate field names before building the string. - Variable not in scope. Symptom:
Variable does not exist: stageName. Cause: the bind variable is declared in a different method or block than theDatabase.querycall. Fix: declare it in the same scope, or useDatabase.queryWithBinds(covered later), which takes the values in a map. - Binding an expression. Symptom: a bind error when writing
:wrapper.value. Fix: assign it to a local variable first. - Assuming a typed result.
Database.queryreturnsList<SObject>. If the object is chosen at run time, work withSObjectmethods such asget(String)instead of casting to a type you cannot know. - Leading or trailing spaces. When joining fragments, a missing space (for example
'FROM Account' + 'WHERE ...') produces a syntax error. Put a space at the start of each appended fragment, as in' WHERE '. - Using dynamic SOQL by habit. If a query is dynamic only to insert a value, rewrite it as static SOQL. You get compile-time checks and dependency tracking back.
A working rule
Pick the least dynamic option that solves the problem:
- If only values vary, write static SOQL with bind variables.
- If the structure varies, use dynamic SOQL. Put values in bind variables.
- Build field, object and sort names only from fixed literals or from names you have validated.
Summary
Static SOQL is checked when you save, tracked for dependencies, and safe from injection because its structure is fixed. Dynamic SOQL is a string passed to Database.query or Database.countQuery, which lets the structure vary but moves checking to run time and makes untrusted input dangerous. Use dynamic SOQL only when fields, objects, filters or sort order must change at run time. If only a value changes, keep the query static and bind the value.
Exercise
A developer writes a method that takes a String last name and builds 'SELECT Id FROM Contact WHERE LastName = \'' + lastName + '\'', then runs it with Database.query. Only the last name varies. What is the better approach, and why?
Show answer
Rewrite it as static SOQL with a bind variable: [SELECT Id FROM Contact WHERE LastName = :lastName]. Only a value changes, so dynamic SOQL is not needed. The static form is checked at compile time, tracked for field dependencies, and the value is passed as data, so it cannot change the query structure.
Exercise
A list view component lets users pick any sortable field and click to sort. Which part of the query can be handled with a bind variable, and which part cannot? What does that mean for the query type?
Show answer
Filter values (for example WHERE Industry = :industry) can be bound. The sort field name in ORDER BY is an identifier, not a value, so it cannot be bound. The query structure depends on user choice, so you need dynamic SOQL. The field name must come from a fixed list or a Schema describe lookup, not directly from user input.
Exercise
Why does a misspelled field name in Database.query('SELECT Id, Nme FROM Account') fail differently from [SELECT Id, Nme FROM Account]?
Show answer
Static SOQL is compiled when the class is saved, so the typo prevents saving. In dynamic SOQL the query is only a string until Database.query runs, so the error appears at run time as a System.QueryException and only if that line executes.