Bind Variables
By the end of this lesson, you'll be able to:
- Use a bind variable to insert an Apex variable's value into a SOQL query
- Explain why bind variables are safer than manually building query strings
- Use a bind variable with a collection to match against multiple values
Prerequisites: "SOQL For Loops"
Using a bind variable
String targetIndustry = 'Technology';
List<Account> accounts = [
SELECT Id, Name FROM Account
WHERE Industry = :targetIndustry
];
The colon before targetIndustry marks it as a bind variable — Apex substitutes the variable's actual value into the query at runtime. This is how every dynamic filter value gets into a SOQL query, rather than manually building a query as a raw String.
Binding a collection with IN
Set<String> targetIndustries = new Set<String>{'Technology', 'Finance', 'Healthcare'};
List<Account> accounts = [
SELECT Id, Name FROM Account
WHERE Industry IN :targetIndustries
];
IN :targetIndustries matches any Account whose Industry is present in the Set — this is exactly the pattern from Module 18's "Maps of sObjects" lesson (WHERE Id IN :accountIds), now explained directly: a Set or List bind variable paired with IN is the standard way to query "any of these values."
Why bind variables matter for safety
// SAFE — the value is bound, not concatenated into the query text
List<Account> accounts = [SELECT Id FROM Account WHERE Name = :userSuppliedName];
// RISKY — building the query as a raw String (covered next lesson)
String query = 'SELECT Id FROM Account WHERE Name = \'' + userSuppliedName + '\'';
Bind variables keep user-supplied values clearly separated from the query's actual structure — this becomes directly important in the next lesson, which covers what can go wrong when query text is built by hand instead.
Exercise
Given Set<Id> targetIds already populated, write a query selecting Id and Name from Contact where Id is in that set.
Show hint
WHERE Id IN :targetIds
Bind Variables Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A bind variable inserts an Apex variable's value directly into a SOQL query using a colon prefix — the standard, safe way to filter a query using dynamic values.