Sub topic 8
Querying related records
This chapter covers how SOQL reads across relationships. You can reach up to a parent through dot notation, and down to children through a subquery. It assumes you can write an inline query with a WHERE clause and bind variables, and that you know how lookup and master-detail relationships connect objects.
Two directions, two syntaxes
SOQL does not use joins. Instead, it follows relationships that already exist on the data model, and the syntax depends on which way you are going.
| Direction | Starting point | Syntax | Result shape |
|---|---|---|---|
| Child to parent | Contact | `Account.Name` (dot notation) | A single parent record on each child |
| Parent to child | Account | `(SELECT ... FROM Contacts)` (subquery) | A list of child records on each parent |
Child to parent with dot notation
When a record has a lookup or master-detail field, you can read fields of the parent in the same query. Use the relationship name, followed by a dot and the parent field.
List<Contact> contacts = [
SELECT Id, LastName, Account.Name
FROM Contact
WHERE Account.Industry = 'Technology'
];
for (Contact c : contacts) {
System.debug(c.LastName + ' works at ' + c.Account.Name);
}The parent field appears in two places. In the SELECT list it returns data. In the WHERE clause it filters the child rows by a parent value.
Relationship names are not field names
For a standard lookup, the relationship name is the field name without Id. The field AccountId gives the relationship Account. For a custom lookup, the field ends in __c, and the relationship name ends in __r.
| Field | Relationship name |
|---|---|
| `Contact.AccountId` | `Account` |
| `Invoice__c.Customer__c` | `Customer__r` |
So a query on a custom object reads SELECT Customer__r.Name FROM Invoice__c. Mixing up __c and __r is a common source of "No such column" errors.
Spanning more than one level
You can chain relationships. SOQL allows up to five levels of parent traversal from a child, for example Contact.Account.Owner.Manager.Name. Each hop adds query cost, so span only as far as you need.
Null parents
If a Contact has no Account, c.Account is null. Reading c.Account.Name on that record throws a NullPointerException. Guard the access.
List<Contact> contacts = [
SELECT Id, LastName, Account.Name
FROM Contact
LIMIT 50
];
for (Contact c : contacts) {
String accountName = c.Account != null ? c.Account.Name : 'No account';
System.debug(c.LastName + ': ' + accountName);
}You can also use the safe navigation operator, which returns null instead of throwing: c.Account?.Name.
Parent to child with a subquery
To get each parent together with its children, put a nested SELECT in parentheses in the outer SELECT list. The subquery's FROM clause uses the plural child relationship name, not the object name.
List<Account> accts = [
SELECT Name, (SELECT LastName, Email FROM Contacts)
FROM Account
WHERE Industry = 'Technology'
];
for (Account a : accts) {
for (Contact c : a.Contacts) {
System.debug(a.Name + ': ' + c.LastName);
}
}Each returned Account carries a list of its Contacts. That list is empty when the Account has none. It is never null, so you can loop over it without a check.
Finding the child relationship name
The plural name is defined on the relationship. For standard objects, it is usually the plural of the child object, such as Contacts, Opportunities, or Cases. For custom objects, it ends in __r, for example Invoices__r. The name is set in the lookup or master-detail field's definition in Setup, in the Child Relationship Name property. If a subquery fails with an invalid relationship error, check that value.
Filtering and ordering inside a subquery
A subquery accepts its own WHERE, ORDER BY, and LIMIT clauses. These apply only to the children and do not remove parents.
List<Account> accts = [
SELECT Name,
(SELECT LastName FROM Contacts
WHERE Email != null
ORDER BY LastName
LIMIT 3)
FROM Account
WHERE Industry = 'Technology'
];This returns every Technology account. Accounts with no matching Contact simply have an empty list.
Keeping only parents that have children
To filter the parents themselves by their children, use a semi-join in the WHERE clause. The inner query must return a single Id column.
List<Account> withContacts = [
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact WHERE Email != null)
];Use NOT IN for an anti-join, which returns parents that have no matching children.
Combining both directions
A single query can go up and down at once. This one returns Accounts, their owner's name, and their open Opportunities.
List<Account> accts = [
SELECT Name, Owner.Name,
(SELECT Name, Amount FROM Opportunities WHERE IsClosed = false)
FROM Account
WHERE Industry = 'Technology'
];
for (Account a : accts) {
System.debug(a.Name + ' owned by ' + a.Owner.Name);
for (Opportunity o : a.Opportunities) {
System.debug(' ' + o.Name + ' ' + o.Amount);
}
}Limits and edge cases
Relationship queries have their own constraints. They also count against the governor limits covered in a later chapter.
- A query counts as one SOQL query, however many relationships it spans. Fetching parents and children in one subquery query uses one query. Querying each separately uses two.
- A query can contain at most 20 parent-to-child subqueries in the SELECT list.
- Records returned by subqueries count toward the total rows retrieved, not only the parent rows.
- Subqueries on a parent-to-child relationship go one level deep in the SELECT list in standard use. Deeper nesting is available for some combinations of objects, but it is better to query the grandchildren separately.
- Polymorphic fields such as
Task.WhatIdorTask.Ownerpoint to more than one object type. UseTYPEOFor theWhat.Nameform to read them.
Choosing between the two shapes
The choice depends on what you need to loop over.
- Use dot notation when your records are the children and you need one parent value for each, such as a Contact's Account name.
- Use a subquery when your records are the parents and you need all their children together, such as each Account's Opportunities.
- Use a direct query on the child object with
WHERE ParentId IN :idswhen parents are already in memory or when you need to filter or aggregate the children freely.
The last option connects to bulk-safe patterns. Collect parent Ids into a Set, run a single query on the child object, and group the results in a map.
Set<Id> accountIds = new Set<Id>();
for (Account a : [SELECT Id FROM Account WHERE Industry = 'Technology']) {
accountIds.add(a.Id);
}
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Contact c : [SELECT Id, LastName, AccountId FROM Contact WHERE AccountId IN :accountIds]) {
if (!contactsByAccount.containsKey(c.AccountId)) {
contactsByAccount.put(c.AccountId, new List<Contact>());
}
contactsByAccount.get(c.AccountId).add(c);
}
System.debug(contactsByAccount.size() + ' accounts have contacts');Common errors
| Error | Cause | Fix |
|---|---|---|
| `Didn't understand relationship 'Contact' in FROM part of query` | The subquery used the object name instead of the plural relationship name | Use `Contacts` |
| `No such column 'Customer__c.Name'` | Used `__c` for the relationship | Use `Customer__r.Name` |
| `System.NullPointerException` on `c.Account.Name` | The Contact has no Account | Check for null or use `?.` |
| Fields in the subquery are unavailable | The field was not in the subquery's SELECT list | Add it to the subquery |
Exercise
You have a List<Account> from SELECT Name, (SELECT LastName FROM Contacts) FROM Account. An account has no contacts. What does a.Contacts return, and is it safe to loop over it directly?
Show answer
It returns an empty list, not null, so looping over it directly is safe and the loop body simply never runs.
Exercise
Write a query that returns the Id of every Account that has at least one Opportunity, without selecting any Opportunity fields into the results.
Show answer
[SELECT Id FROM Account WHERE Id IN (SELECT AccountId FROM Opportunity)]. This is a semi-join, so the child query is used only to filter parents.