Sub topic 8
Reading parent and child data from results in Apex
This chapter assumes you can write basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT). It also assumes you know the difference between lookup and master-detail relationships, and that you can read basic Apex: variables, for loops, lists, and maps. Earlier chapters showed how to write child-to-parent queries with dot notation and parent-to-child queries with subqueries. Here you will read the results in Apex without hitting a NullPointerException or an SObjectException.
What the query returns
An Apex query returns sObjects. Related data is not flattened into extra columns. It is stored as nested objects inside each record:
- Child-to-parent: the parent is a single sObject stored in the relationship field. For
Contact,c.Accountis anAccount. For a custom lookup,t.Project__ris aProject__c. - Parent-to-child: the children are a
Listof sObjects stored under the child relationship name. ForAccount,a.Contactsis aList<Contact>. For custom objects,p.Tasks__ris aList<Task__c>.
The relationship name is the property name in Apex, as it is in SOQL. Case does not matter, but spelling does. Project__r is correct and Project__c is the field that holds the ID.
Reading parent fields
Dot notation works the same way in Apex as in SOQL. The query determines which parent fields are loaded.
List<Contact> contacts = [
SELECT Id, LastName, Account.Name, Account.Owner.Name
FROM Contact
LIMIT 10
];
for (Contact c : contacts) {
String accountName = c.Account?.Name;
String ownerName = c.Account?.Owner?.Name;
System.debug(c.LastName + ' / ' + accountName + ' / ' + ownerName);
}The ?. operator is safe navigation. If the expression to its left is null, the whole expression is null instead of throwing an error. Each link in the chain can be empty, so each link needs ?.. A contact with no account has c.Account == null, and c.Account.Name would throw a System.NullPointerException.
The same code works without safe navigation if you check first:
Contact c = [SELECT Id, Account.Name FROM Contact WHERE AccountId != null LIMIT 1];
String accountName = c.Account.Name;This is safe only because the WHERE clause guarantees the lookup is filled in. The check for an empty lookup belongs in either the query or the code. Relying on "all my test data has an account" is the usual cause of production errors.
Parent fields you did not query
A relationship is only populated when the query asks for it.
| Situation | Result in Apex |
|---|---|
| Parent relationship not in the `SELECT` list | `c.Account` is `null` |
| Parent relationship queried, field not queried | Reading `c.Account.Industry` throws `System.SObjectException` |
| Lookup field is empty on this record | `c.Account` is `null` |
| Parent field is queried and has no value | `c.Account.Name` is `null`, with no error |
The first and the third rows look identical in code. Both give a null parent. If you see a null where you expected data, check the SELECT list before you check the data.
The ID field itself is always available. c.AccountId is a normal field on Contact, and you can read it without querying the parent. Use it when you only need the ID, which keeps the query smaller.
Reading child records
A subquery in the SELECT list fills a list on each parent. Iterate it like any other list.
for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts) FROM Account LIMIT 10]) {
System.debug(a.Name + ' has ' + a.Contacts.size() + ' contacts');
for (Contact c : a.Contacts) {
System.debug(c.LastName);
}
}When a parent has no children, a.Contacts is an empty list, not null. So a.Contacts.size() and a for loop are both safe. Indexing is not safe: a.Contacts[0] on an empty list throws a System.ListException. Check isEmpty() first.
for (Account a : [SELECT Id, Name, (SELECT Id, LastName FROM Contacts) FROM Account LIMIT 20]) {
if (a.Contacts.isEmpty()) {
System.debug(a.Name + ' has no contacts');
} else {
System.debug(a.Name + ' first contact: ' + a.Contacts[0].LastName);
}
}If the subquery was not in the query, the child relationship is not loaded. Reading a.Contacts then throws an SObjectException, not a null result. Parents have lists and children have single objects, so the failure modes differ. Remember that the shape of the data follows the direction you queried.
Which direction to use
| You have | You want | Query |
|---|---|---|
| A list of contacts | Each one's account name | Child-to-parent, `Account.Name` |
| A list of accounts | All contacts of each | Parent-to-child, `(SELECT ... FROM Contacts)` |
| Accounts, and only those with contacts | Filtered parents | Semi-join, covered in a later chapter |
Custom objects
The same rules apply to custom relationships. The names carry the __r suffix.
List<Task__c> tasks = [
SELECT Id, Name, Project__r.Name
FROM Task__c
WHERE Project__r.Status__c = 'Active'
];
for (Task__c t : tasks) {
System.debug(t.Name + ' belongs to ' + t.Project__r?.Name);
}
for (Project__c p : [SELECT Id, Name, (SELECT Id, Name FROM Tasks__r) FROM Project__c]) {
System.debug(p.Name + ': ' + p.Tasks__r.size() + ' tasks');
}Notice that Project__r.Status__c is used in the WHERE clause but not in the SELECT list. Filtering on a parent field does not load it. Reading t.Project__r.Status__c in Apex would throw an SObjectException here, because the query never selected it.
These examples use the custom objects Task__c and Project__c from earlier chapters, so they run only in an org that has them. The Account and Contact examples run in any org.
Building a map from child results
A common pattern is to turn nested results into a map, so other code can look up children by parent ID without loops inside loops.
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Account a : [
SELECT Id, Name, (SELECT Id, LastName FROM Contacts)
FROM Account
WHERE Industry = 'Technology'
LIMIT 20
]) {
contactsByAccount.put(a.Id, a.Contacts);
}
for (Id accountId : contactsByAccount.keySet()) {
System.debug(accountId + ' -> ' + contactsByAccount.get(accountId).size());
}Because every parent gets a list, even an empty one, contactsByAccount.get(id) never returns null for an ID in the map. Check containsKey only for IDs that were not part of the query.
Changing related data
Query results are copies. Changing a field on a parent that you read through a child does not save anything.
Contact c = [SELECT Id, Account.Name FROM Contact WHERE AccountId != null LIMIT 1];
c.Account.Name = 'Renamed'; // changes the in-memory copy only
update c; // updates the Contact, not the AccountTo change the account, collect the account records and update them in their own DML statement:
Account parent = new Account(Id = c.AccountId, Name = 'Renamed');
update parent;Updating the child does not write the nested parent data back. Likewise, adding an item to a.Contacts does not create a contact. Insert the new Contact with its AccountId set.
Reading results dynamically
When the object or relationship is not known at compile time, use the generic SObject methods.
SObject acc = Database.query('SELECT Id, Name, (SELECT LastName FROM Contacts) FROM Account LIMIT 1')[0];
List<SObject> kids = acc.getSObjects('Contacts');
if (kids != null) {
for (SObject k : kids) {
System.debug(k.get('LastName'));
}
}
SObject child = Database.query('SELECT Id, Account.Name FROM Contact WHERE AccountId != null LIMIT 1')[0];
SObject parent = child.getSObject('Account');
System.debug(parent.get('Name'));getSObjects takes the child relationship name and returns null when there are no children, unlike a.Contacts, which returns an empty list. This difference catches many people, so the check for null above is needed. For cross-object paths, getSObject('Account') returns one level. For deeper paths, call it once per level and check each result for null.
Common mistakes
- Using the field name instead of the relationship name.
c.AccountId.Namedoes not compile. Usec.Account.Name. - Calling a child list as if it were one record.
a.Contacts.LastNamefails. Loop over the list or index into it. - Indexing an empty list. Use
isEmpty()orsize()before[0]. - Querying the parent field in
WHEREand reading it later. Filtering does not select. Add the field to theSELECTlist. - Expecting a parent update to persist. Update the parent in its own DML statement.
Exercise
A query is SELECT Id, Name, (SELECT LastName FROM Contacts) FROM Account. For an account with no contacts, what do a.Contacts.size() and a.Contacts[0].LastName do, and what would a.getSObjects('Contacts') return?
Show answer
a.Contacts.size() returns 0, because a queried child relationship is an empty list, not null. a.Contacts[0].LastName throws a System.ListException, because the list has no element at index 0. a.getSObjects('Contacts') returns null for the same record, so the result must be checked for null before looping.
Exercise
Rewrite String n = c.Account.Owner.Name; so that it never throws when the contact has no account, and explain why the query must also contain Account.Owner.Name.
Show answer
Write String n = c.Account?.Owner?.Name;. Each ?. returns null if the value on its left is null. The query must select Account.Owner.Name because related data is loaded only for the paths in the SELECT list. Without it, c.Account is null, or reading Owner.Name throws an SObjectException.