Sub topic 4
Using bind variables
A bind variable lets a SOQL query use the value of an Apex expression. You write a colon before the expression, and Apex passes the value to the query at run time. This chapter covers where binds are allowed, how Apex treats different types, and the errors you are most likely to hit.
This chapter assumes you can write an inline query in square brackets, filter it with WHERE, and work with List, Set, and Map in Apex.
The working model
In a static query (one written in square brackets), Apex checks the query at compile time. The text after a colon is parsed as an Apex expression. When the query runs, Apex evaluates that expression and sends the result to the database as a value. The value is never spliced into the query text, so it cannot change the structure of the query.
Because the query text and the value stay separate, a bind variable is both the readable way and the safe way to filter on a runtime value.
A basic bind
String industry = 'Energy';
Decimal minRevenue = 1000000;
List<Account> accts = [
SELECT Id, Name
FROM Account
WHERE Industry = :industry AND AnnualRevenue > :minRevenue
];
System.debug(accts.size() + ' accounts found');The variable name does not need to match the field name. Apex finds industry in the current scope, and the name is not case sensitive. If no variable of that name is in scope, the code fails to compile with a "Variable does not exist" error.
What can follow the colon
A bind is not limited to a simple variable. It can be any Apex expression that produces a value, including field access on an sObject, a list index, or a map lookup.
Account parent = [SELECT Id, Name FROM Account LIMIT 1];
List<String> lastNames = new List<String>{ 'Smith', 'Jones' };
Map<String, Integer> limits = new Map<String, Integer>{ 'contacts' => 5 };
List<Contact> contacts = [
SELECT Id, LastName
FROM Contact
WHERE AccountId = :parent.Id
OR LastName = :lastNames[0]
LIMIT :limits.get('contacts')
];Here :parent.Id reads a field, :lastNames[0] indexes a list, and LIMIT :limits.get('contacts') evaluates a method call. Complex expressions are harder to read, so assign them to a local variable first when the query gets crowded.
Where binds are allowed
| Position | Example | Allowed |
|---|---|---|
| Filter value in `WHERE` | `Name = :n` | Yes |
| Collection after `IN` or `NOT IN` | `Id IN :ids` | Yes |
| `LIMIT` and `OFFSET` values | `LIMIT :max` | Yes |
| Search string in `FIND` (SOSL) | `FIND :term` | Yes |
| Field name in `SELECT` or `WHERE` | `SELECT :field` | No |
| Object name in `FROM` | `FROM :objectName` | No |
A bind supplies a value only. To choose a field or object at run time, you need dynamic SOQL, which is covered in a later chapter.
Binding collections with IN
The = operator compares one value. To match against many values, bind a List or Set to IN.
Set<String> industries = new Set<String>{ 'Technology', 'Energy' };
List<Account> accts = [
SELECT Id, Name, Industry
FROM Account
WHERE Industry IN :industries
];This pattern is the basis of bulk-safe code, because one query serves any number of values. A Set<Id> is the usual choice for record Ids, since a set removes duplicates for you.
Binding a collection to = does not work:
// Compile error: the list type does not match the Industry field
// List<Account> bad = [SELECT Id FROM Account WHERE Industry = :industries];An empty collection with IN is valid and returns no rows. It does not return everything.
Strings, wildcards, and LIKE
With LIKE, you build the pattern in Apex and bind the finished string.
String term = 'acme';
String pattern = '%' + term + '%';
List<Account> matches = [
SELECT Id, Name FROM Account WHERE Name LIKE :pattern
];The % wildcards are part of the bound value, not the query text. Because a bind is never parsed as SOQL, the user's input cannot add clauses. It can still contain % and _, which LIKE treats as wildcards. If the input comes from a user and you want a literal match, escape those characters yourself.
Null values
A null bind does not skip the filter. It filters for records where the field is empty.
Id accountId = null;
List<Contact> orphans = [
SELECT Id, LastName FROM Contact WHERE AccountId = :accountId
];This query returns contacts that have no account. That is sometimes what you want, but it often surprises people when a variable was supposed to hold a value and did not. If a null should mean "no filter", check it in Apex and choose the query to run.
Id accountId = null;
List<Contact> results;
if (accountId == null) {
results = [SELECT Id, LastName FROM Contact LIMIT 200];
} else {
results = [SELECT Id, LastName FROM Contact WHERE AccountId = :accountId];
}Dates and other types
The variable type must be compatible with the field type. Bind a Date to a date field and a Datetime to a datetime field.
Datetime cutoff = Datetime.now().addDays(-30);
List<Account> recent = [
SELECT Id, Name FROM Account WHERE CreatedDate >= :cutoff
];Use a bind when the date is computed in Apex. For fixed ranges such as the last 30 days, a date literal is simpler, and a later chapter covers those.
Binds in LIMIT, OFFSET, and subqueries
LIMIT and OFFSET take an Integer bind. Binds also work inside subqueries, and the same variable can appear more than once.
Integer pageSize = 20;
Integer skip = 40;
String industry = 'Technology';
List<Account> page = [
SELECT Name, (SELECT LastName FROM Contacts WHERE LastName != :industry)
FROM Account
WHERE Industry = :industry
ORDER BY Name
LIMIT :pageSize OFFSET :skip
];Binds in dynamic queries
Database.query can also see local variables by name, so a query string can contain :name. This works when the query runs in the same scope where the variable is defined. Database.queryWithBinds takes the values in an explicit map, which makes the dependency visible.
String name = 'Acme';
String soql = 'SELECT Id, Name FROM Account WHERE Name = :name';
List<Account> viaScope = Database.query(soql);
List<Account> viaMap = Database.queryWithBinds(
soql,
new Map<String, Object>{ 'name' => name },
AccessLevel.USER_MODE
);Prefer queryWithBinds when the query string is built or passed between methods, because it does not depend on variable scope.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "Variable does not exist" at compile time | The bound variable is out of scope or misspelled | Declare it in the enclosing scope |
| Type mismatch compile error | A list was bound to `=`, or the types differ | Use `IN` for collections and match the field type |
| Query returns records with an empty field | A null variable was bound with `=` | Check for null before running the query |
| Query returns nothing | An empty set was bound to `IN` | Confirm the collection is populated first |
| `SELECT :field` is rejected | Binds supply values, not field or object names | Use dynamic SOQL |
Exercises
Exercise
Why does WHERE Industry = :industry protect against injection when industry holds user input, while '... WHERE Industry = \'' + industry + '\'' does not?
Show answer
With a bind, Apex passes the value to the database separately from the query text, so the value is never parsed as SOQL. With concatenation, the input becomes part of the query text, so a crafted value like x' OR Name != ' can change the query's logic.
Exercise
A method receives an Id parentId that may be null. The query [SELECT Id FROM Contact WHERE AccountId = :parentId] returns many contacts when parentId is null. Why, and how do you fix it?
Show answer
A null bind with = matches records where AccountId is empty, so the query returns contacts with no account. Check parentId == null in Apex and return an empty list (or run a different query), and run the filtered query only when it has a value.