Sub topic 1
Static vs dynamic SOQL: when you need a query built at run time
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, lists and sObjects.
- Explain in general terms what sharing rules and field-level security do.
Two ways to run a query
Salesforce Object Query Language (SOQL) queries in Apex come in two forms.
Static SOQL is written in square brackets. The compiler parses it when you save the class.
List<Account> accounts = [
SELECT Id, Name
FROM Account
WHERE Industry = 'Energy'
LIMIT 50
];Dynamic SOQL is a query held in a String and parsed only when the code runs. You pass the string to Database.query.
String soql = 'SELECT Id, Name FROM Account WHERE Industry = \'Energy\' LIMIT 50';
List<Account> accounts = Database.query(soql);Both queries return the same rows. The difference is when Salesforce checks the query.
What the compiler checks for you
With static SOQL, the platform validates the query at save time:
- Object and field names must exist.
- Syntax errors fail the deploy.
- Dependencies are tracked, so you cannot delete a field that a static query uses.
- Bind variables such as
:industryare type-checked against your Apex variables.
With dynamic SOQL, none of that happens until the line runs. A typo like Nmae compiles cleanly and throws a QueryException in production. The compiler also cannot see which fields the string uses, so it cannot protect you from deleting one.
The string is also ordinary text that your code assembles. If any part of it comes from a user, a request parameter or a stored record, that part can change what the query means. The next chapters cover this risk, called SOQL injection, and its fixes.
When you need dynamic SOQL
Prefer static SOQL. Use dynamic SOQL only when the structure of the query is not known until run time. Typical cases:
- Optional filters. A search form where the user may fill in any combination of fields.
- User-chosen sort. The
ORDER BYfield or direction comes from a column header click. - Configurable field lists. An admin picks which fields to show, for example through custom metadata.
- Generic code. A utility that works on any object, where the object name is a parameter.
A static query cannot do these. Bind variables can replace a value, but they cannot replace a field name, an object name or a sort direction.
A worked example: optional filters
Suppose a search accepts an optional industry and an optional minimum employee count. A single static query handles missing values awkwardly. Dynamic SOQL lets you add only the conditions you need.
public with sharing class AccountSearch {
public static List<Account> search(String industry, Integer minEmployees) {
List<String> conditions = new List<String>();
if (String.isNotBlank(industry)) {
conditions.add('Industry = :industry');
}
if (minEmployees != null) {
conditions.add('NumberOfEmployees >= :minEmployees');
}
String soql = 'SELECT Id, Name FROM Account';
if (!conditions.isEmpty()) {
soql += ' WHERE ' + String.join(conditions, ' AND ');
}
soql += ' LIMIT 50';
return Database.query(soql);
}
}Look at what goes into the string. Every piece is a fixed literal written by the developer. The user's values never enter the text. :industry and :minEmployees are bind variables, and Database.query reads their values from the local variables of the same names. This is why the example is safe, and it is the pattern the rest of the tutorial builds on.
Common mistakes
- Choosing dynamic SOQL out of habit. If only values change, a static query with binds is shorter, checked at compile time and safe by construction.
- Building the whole query from raw input. Treat the string as code, not as a message. Fixed text goes in the string, and values go in through binds.
- Expecting early errors. Test every branch that builds a different query, because a bad branch fails only when it runs.
- Forgetting that bind variables need a variable in scope. The name after the colon must be a local variable, parameter or field visible where
Database.queryis called.
Exercise
A page lets users choose whether to sort accounts by Name or by Industry. Can you do this with one static SOQL query and a bind variable for the sort field? If not, what do you use?
Show answer
No. Bind variables can replace values in a WHERE clause, but not field names in ORDER BY. You need dynamic SOQL, with the sort field chosen from a fixed list of allowed names in your code, not copied from user input.
Exercise
Name two things the compiler checks for a static query that it cannot check for a dynamic one.
Show answer
Any two of: that the object and field names exist, that the syntax is valid, that bind variable types match, and that fields used by the query are tracked as dependencies so they cannot be deleted.