Sub topic 12
Combining Both Directions in One Query
This chapter assumes you can write a child-to-parent query with dot notation and a parent-to-child subquery with a child relationship name. It also assumes you can read basic Apex. Here you will put both directions into a single statement, read the result in Apex, and learn which combinations Salesforce allows.
Why combine directions
Most real screens need data from both sides of a record. A contact detail page might show:
- The contact's account name and the account owner (parents).
- The contact's most recent cases (children).
Without a combined query, you would run one query per direction and stitch the results together by ID. A single relationship query returns the records already nested, and it uses one SOQL query instead of several against the governor limit.
Two building blocks make this possible:
- Dot notation works anywhere a field name works in the outer query's
SELECT,WHERE, andORDER BY. - A subquery in the
SELECTlist is evaluated against its own object, so it can use dot notation to reach that child object's parents.
The basic combined query
This query starts at Contact. It reads parent fields upward and child records downward.
SELECT Id, LastName,
Account.Name, Account.Owner.Name,
(SELECT Id, Subject, Status FROM Cases ORDER BY CreatedDate DESC LIMIT 3)
FROM Contact
WHERE Account.Industry = 'Technology'
ORDER BY Account.NameThe query has three parts:
Account.NameandAccount.Owner.Nameare child-to-parent paths. They use the relationship nameAccountand thenOwner, each separated by a dot.(SELECT ... FROM Cases ...)is a parent-to-child subquery.Casesis the child relationship name onContact, not an object API name you invented.- The
WHEREandORDER BYclauses of the outer query filter and sort on the parent fieldAccount.IndustryandAccount.Name. They apply to contacts, not to the cases in the subquery.
Parent paths inside a subquery
The subquery's FROM object is the starting point for its own paths. In the contact query above, you could add Owner.Name to the Cases subquery, and it would mean the owner of each case, not the owner of the contact.
A more useful example goes down from an opportunity and then up from its line items:
SELECT Id, Name, Account.Name,
(SELECT Id, Quantity, PricebookEntry.Product2.Name
FROM OpportunityLineItems)
FROM Opportunity
WHERE StageName = 'Closed Won'Here the outer query goes up to Account. The subquery goes down to OpportunityLineItems, and from each line item it goes up two levels through PricebookEntry to Product2. The result is a tree of opportunities. Each opportunity has an account name and a list of line items, and each line item has a product name.
Starting from the parent instead
You can build the same kind of tree from the top. This query starts at Account, reads the account owner, and brings back both contacts and opportunities. Each child list also includes the child record's owner.
SELECT Id, Name, Owner.Name,
(SELECT Id, LastName, Owner.Name FROM Contacts),
(SELECT Id, Name, StageName, Owner.Name FROM Opportunities WHERE IsClosed = false)
FROM Account
WHERE Id IN (SELECT AccountId FROM Opportunity WHERE StageName = 'Closed Won')This statement uses three techniques from earlier chapters:
- A parent path in the
SELECTlist (Owner.Name). - Two sibling subqueries, each with its own filter where needed.
- A semi-join in the
WHEREclause that keeps only accounts with a won opportunity.
Choose the starting object by asking which records you want one row per. The starting object is the one the query returns as its top-level list. In the contact query you get one row per contact. In this account query you get one row per account, and a contact appears only inside its account's Contacts list.
Reading the result in Apex
Both directions come back as nested sObjects. Parent data is a single sObject reached by dot access. Child data is a list reached through the child relationship name.
List<Contact> contacts = [
SELECT Id, LastName, Account.Name, Account.Owner.Name,
(SELECT Id, Subject FROM Cases ORDER BY CreatedDate DESC LIMIT 3)
FROM Contact
WHERE Account.Industry = 'Technology'
LIMIT 20
];
for (Contact c : contacts) {
String accountName = c.Account?.Name ?? 'No account';
String ownerName = c.Account?.Owner?.Name ?? 'No owner';
System.debug(c.LastName + ' | ' + accountName + ' | ' + ownerName
+ ' | cases: ' + c.Cases.size());
for (Case k : c.Cases) {
System.debug(' ' + k.Subject);
}
}Three points about this code:
- A parent that does not exist is
null, soc.Account.Owner.Namecan throw a null-reference error. Safe navigation (?.) and the null-coalescing operator (??) avoid it. This query filters onAccount.Industry, so every returned contact has an account. The guard still protects you if you later change the filter. - A child list with no matching records is an empty list, not
null. You can callc.Cases.size()or loop over it safely. - Only the fields you selected are readable. Reading
c.Account.Phonehere throws aSystem.SObjectExceptionbecausePhonewas not in the query.
Filtering one direction by the other
Combining directions raises a common question: does a WHERE clause on the child limit the parents? It depends on where you put it.
| Where the filter sits | What it limits |
|---|---|
| `WHERE` in the subquery | Only the child records returned inside each parent. Parents with no matching children still appear, with an empty list. |
| `WHERE` with a semi-join (`Id IN (SELECT ...)`) | The parents returned. Parents without a matching child disappear. |
| `WHERE` with a parent path (`Account.Industry = ...`) | The child records returned, when the query starts at the child. |
To get "accounts that have open opportunities, and show me only those opportunities," you need both: a semi-join to remove accounts, and a subquery filter to trim the list.
SELECT Id, Name,
(SELECT Id, Name, Amount FROM Opportunities WHERE IsClosed = false)
FROM Account
WHERE Id IN (SELECT AccountId FROM Opportunity WHERE IsClosed = false)Limits and shape restrictions
Combined queries are where relationship limits start to matter. These are the figures commonly documented for SOQL. Check the current SOQL limits page for your API version before you rely on them.
| Limit | Value |
|---|---|
| Child-to-parent relationships in one query | 55 |
| Parent-to-child relationships (subqueries) in one query | 20 |
| Levels of child-to-parent traversal in one path | 5 |
| Levels of parent-to-child nesting | 5 in recent API versions, 1 in older ones |
Some limits come from the shape of SOQL rather than from a counter:
- You cannot write a dotted path that goes down.
Account.Contacts.LastNameis invalid. Going down always needs a subquery. - You cannot go up, then down, in a single path. To get an account's other contacts from a contact, start at
Accountand use a subquery, or run a second query. - Each subquery uses its child relationship name, which is plural for standard objects (
Contacts) and ends in__rfor custom ones (Tasks__r). - Child records returned in subqueries still count as rows retrieved. In Apex, they add to the total rows governor limit. A query that returns 200 accounts with 100 contacts each is far larger than it looks.
Common mistakes
- Using the field name instead of the relationship name.
AccountId.Namefails. UseAccount.Name. For custom lookups, useProject__r.Name, notProject__c.Name. - Guessing the child relationship name. If
FROM Contactfails inside a subquery, the child relationship name isContacts. Look it up on the lookup field's definition, or in the object's Child Relationships list. - Assuming a subquery filter removes parents. It only trims the child list. Use a semi-join to remove parents.
- Dereferencing a null parent. Any lookup that can be empty needs
?.before you read a field from it. - Reading an unqueried field. The result contains only the fields in the
SELECTlist, at every level. - Pulling too much. Wide trees with several subqueries are convenient, but they can hit row and heap limits. Add
LIMITto the outer query and to each subquery, and select only the fields you will use.
Exercise
You need one row per Account, with the account owner's name and the names of its open Opportunities, but only for accounts that have at least one open Opportunity. Write the query.
Show answer
SELECT Id, Name, Owner.Name, (SELECT Id, Name FROM Opportunities WHERE IsClosed = false) FROM Account WHERE Id IN (SELECT AccountId FROM Opportunity WHERE IsClosed = false). Owner.Name is a child-to-parent path. The subquery uses the child relationship name Opportunities, and its WHERE trims the list. The semi-join in the outer WHERE removes accounts with no open opportunity.
Exercise
In Apex, a query selects Contact fields, Account.Name, and a subquery over Cases. For a contact with no account and no cases, what does c.Account?.Name return, and what does c.Cases.size() return?
Show answer
c.Account?.Name returns null, because the missing parent is null and safe navigation stops the lookup. c.Cases.size() returns 0, because a subquery with no matching children gives an empty list, not null.