Sub topic 5
Walking up several parent levels
A child-to-parent query can follow more than one relationship in a single path. This chapter covers how to build those paths, how they behave when a link is empty, and what limits apply. It assumes you can already write a basic child-to-parent query such as Account.Name from a Contact. It also assumes you know how relationship names differ from field names.
What a multi-level path is
A one-level path reads a field from the direct parent: Account.Name on a Contact. A multi-level path chains relationship names with dots, and each dot moves one step up. The final segment is a field name. Every segment before it is a relationship name.
Take a Contact. Its Account relationship leads to the account. The account's Owner relationship leads to a User. That user's Manager relationship leads to another User. From the contact, the path to the manager's name is Account.Owner.Manager.Name.
Here is the query:
SELECT Id, LastName,
Account.Name,
Account.Owner.Name,
Account.Owner.Manager.Name
FROM Contact
WHERE Account.Industry = 'Technology'Each row carries values from three different records besides the contact: the account, the account owner, and the owner's manager. The query needs no extra queries and no joins that you write yourself. Salesforce resolves the chain on the server.
Standard objects and self-references
Two patterns come up often.
The first is the owner hierarchy. Owner on most standard objects leads to a User, and User has a Manager lookup to another User. That makes it possible to climb the reporting line.
The second is a self-referencing lookup. Account has ParentId, whose relationship name is Parent. Each step of Parent goes up one level in the account hierarchy:
SELECT Id, Name,
Parent.Name,
Parent.Parent.Name,
Parent.Parent.Parent.Name
FROM Account
WHERE Parent.Parent.Name != nullThis returns accounts that sit at least two levels below the top of their hierarchy, with the names of up to three ancestors.
| Path from Contact | Meaning |
|---|---|
| `Account.Name` | Name of the contact's account |
| `Account.Owner.Name` | Name of the user who owns that account |
| `Account.Owner.Manager.Name` | Name of that user's manager |
| `Account.Parent.Name` | Name of the account's parent account |
| `Account.Parent.Owner.Email` | Email of the parent account's owner |
Custom objects
Custom lookups follow the same pattern, but each relationship name ends in __r. The field name ends in __c, and you replace that suffix with __r to traverse it.
Suppose Task__c has a lookup Project__c, and Project__c has a lookup Program__c. The path to the program's name is:
SELECT Id, Name,
Project__r.Name,
Project__r.Program__r.Name,
Project__r.Program__r.Owner.Name
FROM Task__c
WHERE Project__r.Program__r.Status__c = 'Active'You can mix custom and standard relationships in one path. The last line above goes from a custom Program__c to its standard Owner, which has no suffix.
Filtering and sorting at depth
A deep path works anywhere a field can appear: SELECT, WHERE, and ORDER BY.
SELECT Id, LastName, Account.Owner.Name
FROM Contact
WHERE Account.Owner.Manager.Name = 'Dana Ortiz'
ORDER BY Account.Owner.Name, LastNameFiltering on a deep field has a side effect. Salesforce reads each link in the chain as an optional join, so a contact with no account still appears in a query that only selects parent fields. Once you add a WHERE condition on a parent field, a missing link means the field has no value, and the comparison fails. Those rows then drop out.
What happens when a link is empty
A lookup field can be empty. When it is, everything above it is empty too.
- If a
Contacthas noAccount, thenAccount.Owner.Manager.Nameis null for that row. - If the account exists but its owner has no manager,
Account.Owner.Manager.Nameis null.Account.Owner.Namestill has a value.
Null checks in SOQL therefore match more rows than you might expect:
SELECT Id, LastName
FROM Contact
WHERE Account.Owner.Manager.Name = nullThis returns contacts with no account, contacts whose account owner has no manager, and contacts whose manager has a null name. If you mean only one of those cases, test the specific link. For instance, add AND AccountId != null to rule out contacts with no account.
Reading a deep path in Apex
In Apex, each relationship becomes a nested sObject. c.Account is an Account, c.Account.Owner is a User, and c.Account.Owner.Manager is another User. You can only read what you selected, and you must guard against empty links.
List<Contact> contacts = [
SELECT Id, LastName,
Account.Name,
Account.Owner.Name,
Account.Owner.Manager.Name
FROM Contact
LIMIT 10
];
for (Contact c : contacts) {
String accountName = c.Account?.Name;
String ownerName = c.Account?.Owner?.Name;
String managerName = c.Account?.Owner?.Manager?.Name;
System.debug(c.LastName + ' | ' + accountName + ' | ' + ownerName + ' | ' + managerName);
}The ?. operator returns null as soon as any link in the chain is null. Without it, c.Account.Owner.Manager.Name throws a System.NullPointerException whenever a contact has no account or an owner has no manager. This applies even though the SOQL itself ran without error.
Apex has a second trap. If you select Account.Owner.Name but then read c.Account.Owner.Email, you get a System.SObjectException. The message says the row was retrieved without querying the requested field. Selecting a path does not select the other fields on the records along it.
Limits
Multi-level traversal has hard limits. The values below are the ones in the Salesforce documentation. Check the current SOQL limits for your API version.
| Limit | Value |
|---|---|
| Parent relationship levels in one path (child-to-parent) | Up to 5 |
| Child-to-parent relationships in one query | Up to 55 |
Levels are counted by relationship hops. The field name at the end does not count. Account.Owner.Manager.Manager.Manager.Name uses five hops. A sixth hop makes the query fail.
Fields reached through a path can also be restricted by the user's field-level security and by object permissions. Fields the running user cannot read may cause an error or be returned as null, depending on the execution context. Treat deep paths as a place where permissions can differ from the base object.
Performance also matters. Each hop is another join the platform must resolve. A path through several large objects can be slow, especially in a WHERE clause on a large table. Put selective filters on the object you query from. Add a filter on an indexed field such as Id, a lookup field, or a date, and keep the deepest paths for the SELECT list when you can.
Common mistakes
- Using the field name instead of the relationship name.
Account.OwnerId.Nameis invalid. UseAccount.Owner.Name. - Forgetting
__ron custom hops.Project__c.Namefails. UseProject__r.Name. - Reading unqueried fields in Apex. Select every field you intend to read.
- Skipping null safety. Use
?.or explicit checks on every hop that may be empty. - Treating a null comparison as precise. A null at depth can come from any link in the chain.
- Exceeding five hops. If you need to go further, run a second query using IDs from the first.
Exercise
A query selects Account.Owner.Manager.Name from Contact. In Apex, a loop over the results throws a NullPointerException on the line String m = c.Account.Owner.Manager.Name;. Name two data conditions that can cause this, and write the corrected line.
Show answer
The exception occurs if the contact has no account (c.Account is null) or if the account owner has no manager (c.Account.Owner.Manager is null). The corrected line is String m = c.Account?.Owner?.Manager?.Name;, which returns null as soon as any link is empty.
Exercise
Write a SOQL query on Contact that returns Id and LastName, plus the name of the account's parent account, only for contacts whose account's parent's parent is also set. Keep the query to a legal number of hops.
Show answer
SELECT Id, LastName, Account.Parent.Name FROM Contact WHERE Account.Parent.ParentId != null. The select path uses two hops (Account, Parent). The filter tests the ParentId foreign key on the parent account, so it is true only when a grandparent account exists.