Sub topic 1
Static and Dynamic SOQL
Prerequisites
This chapter assumes basic Apex syntax, classes, strings, collections, sObjects, and static SOQL with WHERE, ORDER BY, and LIMIT. It also assumes a basic understanding of Salesforce sharing and field-level security.
Static vs. Dynamic SOQL
Static SOQL is written directly in Apex. Salesforce checks its structure when the code is compiled. Use it when the object, fields, filters, and query shape are known in advance.
List<Account> accounts = [
SELECT Id, Name
FROM Account
WHERE Industry = 'Technology'
ORDER BY Name
LIMIT 50
];Dynamic SOQL builds a query string at run time. It is useful when the query must change based on configuration or validated choices, such as a selected field or optional filter. Dynamic SOQL has more flexibility, but the query text must be handled carefully.
Running Dynamic Queries
Database.query runs a dynamic SOQL string and returns records. Database.countQuery runs a dynamic count query and returns an integer.
public with sharing class AccountSearch {
public static List<Account> findByIndustry(String industry) {
String soql =
'SELECT Id, Name FROM Account WHERE Industry = :industry LIMIT 50';
return Database.query(soql);
}
public static Integer countByIndustry(String industry) {
String soql =
'SELECT COUNT() FROM Account WHERE Industry = :industry';
return Database.countQuery(soql);
}
}The :industry expression is a bind variable. It sends the value separately from the query text. This distinction is important when the value comes from a user.
How SOQL Injection Works
SOQL injection occurs when untrusted input is concatenated into a query string. The input can add quotes, operators, or other query text.
public static List<Account> findByName(String name) {
String soql =
'SELECT Id, Name FROM Account WHERE Name = \'' + name + '\'';
return Database.query(soql);
}For example, an input such as ' OR Name != ' changes the condition so that many records match. The attacker has changed the query's structure, not merely supplied an account name.
Exercise
When should you prefer static SOQL over dynamic SOQL?
Show answer
Prefer static SOQL when the query structure is known at compile time. Use dynamic SOQL only when the structure must change at run time.