Sub topic 4
Using bind variables
This chapter assumes you can write a basic inline SOQL query in Apex and filter it with WHERE. It builds on the filtering chapter and prepares you for bulk-safe patterns and dynamic SOQL later.
What a bind variable is
A bind variable is an Apex variable you reference inside a query by putting a colon in front of its name. At run time, Apex reads the variable's current value and passes it to the query as data. The value is never pasted into the query text.
String industry = 'Energy';
Decimal minRevenue = 1000000;
List<Account> accts = [
SELECT Id, Name
FROM Account
WHERE Industry = :industry AND AnnualRevenue > :minRevenue
];Here :industry and :minRevenue are bound. If industry held a value such as x' OR Name != ', the query would still look for an Industry that equals that exact string. The value cannot change the structure of the query.
Why use them
- Reuse. You write the query once and change the variables, not the query text.
- Safety. Bound values are treated as data, so they cannot inject extra SOQL.
- Type handling. Apex passes dates, numbers, and Ids with their types. You do not format quotes or date strings yourself.
What you can bind
You can bind a single value, a collection, or an expression. These forms are common:
| Form | Example | Typical use |
|---|---|---|
| Simple variable | `WHERE Name = :acctName` | Equality and comparison |
| Collection | `WHERE Id IN :idSet` | Matching many values with `IN` |
| Field access | `WHERE AccountId = :c.AccountId` | Using a value from a record |
| Method call | `WHERE OwnerId = :UserInfo.getUserId()` | Using a computed value |
Collections are the most important form. A Set<Id> or List<String> bound to IN lets one query match many values, which the bulk-safe chapter relies on.
Set<String> industries = new Set<String>{ 'Energy', 'Technology' };
List<Account> accts = [
SELECT Id, Name FROM Account WHERE Industry IN :industries
];Binding in the LIMIT clause
You can also bind a value in LIMIT, which is handy when the row count is a parameter.
Integer maxRows = 5;
List<Account> accts = [SELECT Id, Name FROM Account LIMIT :maxRows];Common errors
- Quoting the variable. Writing
WHERE Name = ':acctName'compares against the literal text:acctName, not the variable's value. Leave the colon-prefixed name unquoted. - Binding a null.
WHERE Industry = :industrywith a null variable matches records where the field is null, rather than throwing an error. Check for null first if you do not want that. - Mismatched types. Binding a
Stringto a number or Id field can fail at compile or run time. Declare the variable with the field's type. - Binding an empty collection.
IN :emptySetis valid and returns no rows. It does not throw an error, but it still costs a query against the limit.
Scope of binding
Bind variables work in inline queries written in square brackets. In dynamic SOQL, a bind variable in the query string works only if the variable is in scope where Database.query runs. The dynamic SOQL chapter covers Database.queryWithBinds for explicit control.
Exercise
A method receives a Set<Id> named ownerIds and must return all Accounts owned by any of those users. Write the query and say why it is better than looping over the Ids and running one query for each.
Show answer
List<Account> accts = [SELECT Id, Name FROM Account WHERE OwnerId IN :ownerIds]; This runs one SOQL query no matter how many Ids the set holds, so it stays within the limit on queries per transaction. A loop would run one query per Id and fail once it passed 100 synchronous queries.
Exercise
What does the query SELECT Id FROM Account WHERE Name = ':n' compare each account name to, and how do you fix it?
Show answer
It compares Name to the literal text ":n", because the quotes turn the bind variable into a string. Remove the quotes and write WHERE Name = :n.