Sub topic 10
Using collections with SOQL
This chapter assumes you know basic Apex syntax, the Account and Contact SObjects, and simple SOQL SELECT queries. It covers three ways collections work with query results: assigning a query to a List, building a Map from a query, and passing a Set into a query as a bind variable.
Query results are Lists
A SOQL query in square brackets returns a List<SObject>. You can assign it to a typed list, and the query returns an empty list when nothing matches. It never returns null.
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 10];
System.debug(accounts.size());Building a Map from a query
The Map constructor accepts a list of SObjects. It uses each record's Id as the key and the record as the value. This gives you fast lookup by Id without a nested loop.
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 10]
);
Set<Id> accountIds = accountsById.keySet();
List<Contact> contacts = [
SELECT Id, LastName, AccountId
FROM Contact
WHERE AccountId IN :accountIds
];This shortcut only keys by Id. To key by another field, such as an email address, loop over the results and call put yourself.
Bind variables with IN
A colon before a variable name in a query is a bind variable. When the variable is a Set or List, you can use it with IN to filter on many values in a single query. In the example above, keySet() returns a Set<Id>, and :accountIds passes it straight into the WHERE clause.
The flow looks like this:
Why this matters for limits
Each SOQL statement counts against the limit of 100 synchronous queries per transaction. Putting a query inside a loop that runs once per record can exceed that limit quickly. One query with IN :ids replaces many queries, and the Map gives you lookups afterward. The bulkification chapter builds on this.
// Avoid: one query per account
for (Account a : accounts) {
List<Contact> cs = [SELECT Id FROM Contact WHERE AccountId = :a.Id];
}
// Prefer: one query for all accounts
Map<Id, Account> byId = new Map<Id, Account>(accounts);
List<Contact> allContacts = [
SELECT Id, AccountId FROM Contact
WHERE AccountId IN :byId.keySet()
];Common errors
- Reading a field you did not select. If the query selects only
IdandName, readingIndustrythrows aSystem.SObjectException. Add the field to theSELECTlist. - Binding a null collection. An
INfilter with a null variable returns no rows. An empty set does the same. Skip the query when the set is empty. - Assigning a single-row query to one SObject.
Account a = [SELECT Id FROM Account WHERE Name = 'X'];throws aQueryExceptionif zero or several rows match. Use a List when you cannot guarantee one row. - Expecting a Map of a different key type.
new Map<String, Account>(queryResult)does not compile. The constructor form only supportsIdkeys.
Exercise
A trigger receives a List<Contact> named newContacts. Write the lines that collect the AccountId values into a Set<Id> and then query the matching Accounts into a Map<Id, Account> with one query.
Show answer
Set<Id> accountIds = new Set<Id>(); for (Contact c : newContacts) { if (c.AccountId != null) { accountIds.add(c.AccountId); } } Map<Id, Account> accountsById = new Map<Id, Account>( [SELECT Id, Name FROM Account WHERE Id IN :accountIds] );