Sub topic 2
Walking Up Several Parent Levels
Assume you know basic SOQL, Salesforce object relationships, and basic Apex. A relationship query follows a lookup or master-detail relationship to retrieve related records.
Walking up several parent levels
A child-to-parent query starts with the child object and uses dot notation to read fields from its parent. You can continue through additional parent relationships.
SELECT Id, LastName, Account.Name, Account.Owner.Name
FROM Contact
WHERE Account.Industry = 'Technology'
ORDER BY Account.NameThis query starts with Contact, moves to its Account, then moves from the account to its Owner. Parent fields can also be used in WHERE and ORDER BY.
A custom lookup uses __r for the relationship name:
SELECT Id, Name, Project__r.Name
FROM Task__c
WHERE Project__r.Status__c = 'Active'Parent-to-child subqueries
To retrieve children from each parent, place a subquery in the SELECT list. Use the child relationship name, which is usually plural for standard objects and is configured on custom relationships.
SELECT Id, Name,
(SELECT Id, LastName FROM Contacts)
FROM Account
WHERE Industry = 'Technology'The parent-to-child direction returns a list of child records for every parent record.
Clauses inside a subquery
A child subquery can have its own WHERE, ORDER BY, and LIMIT. These clauses apply to the child records, not to the outer parent query.
SELECT Id, Name,
(SELECT Id, LastName
FROM Contacts
WHERE Email != null
ORDER BY LastName
LIMIT 5)
FROM AccountReading results in Apex
A parent relationship is accessed as an sObject. A child relationship is accessed as a list.
for (Account a : [
SELECT Id, Name, AccountNumber,
(SELECT Id, LastName FROM Contacts ORDER BY LastName)
FROM Account
LIMIT 10
]) {
System.debug(a.Name);
for (Contact c : a.Contacts) {
System.debug(c.LastName);
}
}If a lookup is empty, the parent relationship can be null. Safe navigation avoids a null-reference exception.
Contact c = [SELECT Id, Account.Name FROM Contact LIMIT 1];
String accountName = c.Account?.Name;Exercise
Which relationship name belongs in a subquery for contacts related to an Account?
Show answer
Use Contacts, the child relationship name, as in (SELECT Id FROM Contacts).