Sub topic 10
Using collections with SOQL
This chapter assumes you can write a basic SOQL query, know the List, Set, and Map methods from the earlier chapters, and understand that a query returns SObject records. It covers how SOQL and collections feed each other: queries produce Lists, collections feed bind variables, and Maps give you fast lookups on query results.
What a query returns
A SOQL query in square brackets returns a List<SObject>. You can assign it to a typed list, or to a single SObject if you are sure of the row count.
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 5];
System.debug(accounts.size()); // 0 to 5, never nullA query that matches nothing returns an empty list, not null. You can call isEmpty() or loop over the result without a null check.
Only the fields in the SELECT list are populated. Reading another field, such as a.Industry when you did not query it, throws an SObjectException.
Binding collections with IN
A bind variable is an Apex variable referenced in SOQL with a colon prefix. With IN, the bound variable can be a List or a Set. This is how you filter a query by many values in one call.
Set<String> types = new Set<String>{'Customer - Direct', 'Prospect'};
List<Account> matches = [
SELECT Id, Name, Type
FROM Account
WHERE Type IN :types
];Use a Set for filter values. It drops duplicates, so the value list stays small. Lists work too, and List<Id> and Set<Id> are both accepted for Id fields.
If the bound collection is empty, the IN clause matches nothing and the query returns an empty list. It does not fail. That is usually what you want, but note that the query still runs and still counts against your query limit. Guard with isEmpty() if you want to skip it.
Building a Map from a query
The Map constructor accepts a list of SObjects and keys each record by its Id. The key type must be Id, and the value type must match the queried SObject.
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
];
for (Contact c : contacts) {
Account parent = accountsById.get(c.AccountId);
if (parent != null) {
System.debug(c.LastName + ' works at ' + parent.Name);
}
}This pattern does three things at once. The query runs once. The Map gives constant-time lookup by Id inside the loop. The keySet() call produces a Set<Id> for the next query's bind variable.
The constructor shortcut only works for Id keys. If you need another key, such as a name or an external Id, build the Map in a loop:
Map<String, Account> accountsByName = new Map<String, Account>();
for (Account a : [SELECT Id, Name FROM Account LIMIT 100]) {
accountsByName.put(a.Name, a);
}Keys must be unique. If two records share a name, the later put replaces the earlier one without any warning. When a key can repeat, use a Map of Lists instead (see the grouping chapter).
Collecting Ids from related records
A common two-step pattern collects foreign key values from one set of records, then queries the parent or child objects that match.
Set<Id> accountIds = new Set<Id>();
for (Contact c : [SELECT AccountId FROM Contact WHERE Email != null LIMIT 200]) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);The Set removes duplicate Ids, since many contacts can share one account. The null check keeps blank lookups out of the Set.
If you do not need the contact data in Apex, a semi-join subquery does the same job in one query and keeps the Id Set out of heap memory:
List<Account> withContacts = [
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact WHERE Email != null)
];Choose the Set approach when you need the Ids again later, for example to query another object or to compare against trigger records.
Query for loops
You can put the query directly in a for statement. Apex then retrieves records in chunks of 200 instead of loading the whole result into one list.
Integer total = 0;
for (Contact c : [SELECT Id FROM Contact WHERE AccountId != null]) {
total++;
}
System.debug(total);To process one chunk at a time, declare the loop variable as a list:
for (List<Contact> batch : [SELECT Id, LastName FROM Contact]) {
System.debug('Chunk size: ' + batch.size()); // up to 200
}This lowers heap use for large results. It does not raise the 50,000-row limit on total rows retrieved in a transaction.
Subqueries and nested lists
A parent-to-child subquery returns the child records as a List field on each parent.
for (Account a : [
SELECT Id, Name, (SELECT LastName FROM Contacts)
FROM Account
LIMIT 10
]) {
List<Contact> children = a.Contacts;
System.debug(a.Name + ': ' + children.size());
}When an account has no contacts, a.Contacts is an empty list, so the loop needs no null check. The child relationship name (Contacts) is the plural relationship name, not the object name. For custom relationships it ends in __r.
Aggregate results into a Map
Aggregate queries return List<AggregateResult>. Read each value with get(), using the alias you gave the column, and cast it.
Map<Id, Integer> contactCounts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acct, COUNT(Id) total
FROM Contact
WHERE AccountId != null
GROUP BY AccountId
]) {
contactCounts.put((Id) ar.get('acct'), (Integer) ar.get('total'));
}
Integer n = contactCounts.get('001000000000000AAA');
System.debug(n == null ? 0 : n);An account with no contacts has no group row, so get() returns null for it. Treat null as zero when you read the Map.
The query-once flow
Edge cases and gotchas
| Situation | What happens |
|---|---|
| Query returns no rows | Empty list, not null |
| Single-SObject assignment, 0 or 2+ rows | `QueryException` |
| Empty collection in `IN :ids` | Zero rows returned, query still counts toward limits |
| Field not in SELECT | `SObjectException` on read |
| `new Map<Id, SObject>(list)` with duplicate Ids | Later record replaces earlier one |
| Aggregate group with no rows | Key is missing, `get()` returns null |
Keep these limits in mind per transaction: 100 synchronous SOQL queries, 50,000 total rows retrieved, and a 6 MB synchronous heap (12 MB asynchronous). A Map built from a large query holds every record in memory. Select only the fields you need, and prefer a query for loop when you do not need the full list at once.
The most important rule is to keep queries out of loops. Query once into a collection, then look values up in the Map inside the loop.
Exercise
A trigger handler receives a List<Contact> called newContacts. Write the code that collects the non-null AccountId values into a Set, then queries those Accounts into a Map keyed by Id, using exactly one query. Then explain what happens when no contact has an AccountId.
Show answer
Code:
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]
);
When no contact has an AccountId, the Set is empty. The query still runs, counts toward the query limit, and returns zero rows, so the Map is empty and every get() call returns null. You can skip the query with if (!accountIds.isEmpty()) and leave the Map empty.