Sub topic 2
Fixing Injection with Bind Variables
Assume you know basic Apex, static SOQL, strings, collections, and Salesforce sharing and field-level security. This chapter focuses on dynamic SOQL: queries assembled at run time.
Fixing Injection with Bind Variables
A bind variable is an Apex variable that SOQL treats as a value, not as query text. This prevents quotes and operators in user input from changing the query structure.
public with sharing class AccountSearch {
public static List<Account> findByName(String name) {
return Database.query(
'SELECT Id, Name FROM Account WHERE Name = :name'
);
}
}If name contains ' OR Name != ', SOQL searches for that exact account name. It does not add an OR condition.
Database.queryWithBinds and the Bind Map
Database.queryWithBinds takes the query text, a map of bind names to values, and an access mode. The map is useful when a method has several values or when the query is assembled in stages.
public static List<Account> findByIndustry(String industry) {
Map<String, Object> binds = new Map<String, Object>{
'industryValue' => industry
};
return Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Industry = :industryValue',
binds,
AccessLevel.USER_MODE
);
}User mode applies the current user's sharing, object permissions, and field-level permissions.
Convert Input to Typed Values
Convert and validate input before binding it. A typed value limits what the database can interpret.
Id accountId = (Id)inputId;
Integer minimumEmployees = Integer.valueOf(inputCount);
Date createdAfter = Date.valueOf(inputDate);
Boolean active = Boolean.valueOf(inputActive);Handle conversion errors and reject invalid values before running the query. Do not bind unvalidated text where an Id, number, date, or Boolean is expected.
Safe LIKE Searches and Wildcards
Binding protects query structure, but % and _ still have their normal LIKE meaning. Preserve that behavior only when users are allowed to search with wildcards.
String term = '%' + (input == null ? '' : input) + '%';
Map<String, Object> binds = new Map<String, Object>{ 'term' => term };
List<Account> results = Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Name LIKE :term LIMIT 50',
binds,
AccessLevel.USER_MODE
);Allowlist Dynamic Names
Bind variables cannot replace field names, object names, or sort directions. Accept only known identifiers and fixed keywords.
Set<String> allowed = new Set<String>{ 'name', 'industry', 'createddate' };
String field = allowed.contains(sortField?.toLowerCase()) ? sortField.toLowerCase() : 'name';
String direction = directionInput?.equalsIgnoreCase('DESC') ? 'DESC' : 'ASC';
String soql = 'SELECT Id, Name FROM Account ORDER BY ' + field + ' ' + direction;
List<Account> rows = Database.query(soql);For configurable objects or fields, also validate names with Schema describe information before adding them to the query.
Exercise
Can a bind variable safely replace the field name in ORDER BY :field?
Show answer
No. Bind variables represent values. Validate field names with an allowlist and Schema describe data.