Sub topic 8
Reading parent and child data from results in Apex
This chapter assumes you can write basic SOQL with SELECT, FROM, WHERE, ORDER BY, and LIMIT. It also assumes you know basic Apex syntax and the difference between lookup and master-detail relationships. You will read relationship data from query results and avoid the null-reference errors that often come with it.
How query results are shaped
A SOQL query in Apex returns a list of sObjects. When the query includes a relationship, the data is nested inside each record. Which form it takes depends on the direction:
- A child-to-parent query adds the parent as a single nested sObject. You reach it through the relationship name (for example
Account), and then read its fields with dot notation. - A parent-to-child query adds the children as a list. You reach it through the child relationship name (for example
Contacts).
Only the fields you select are populated. If you read a field that the query did not select, Apex throws a System.SObjectException.
Reading child records from a subquery
The child relationship name works like a list field on the parent. It is never null when the subquery was selected. If the parent has no children, you get an empty 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);
}
}Because the list is empty rather than null, a.Contacts.size() is safe and the inner loop simply does not run for accounts with no contacts. You do not need a null check here.
The name must match the child relationship name exactly. For standard objects it is the plural, such as Contacts. For custom objects it ends in __r, such as Tasks__r.
Reading parent fields from a child
For a child-to-parent query, you read the parent through the relationship name and then the field:
Contact c = [SELECT Id, Account.Name FROM Contact WHERE AccountId != null LIMIT 1];
String accountName = c.Account.Name;
Contact c2 = [SELECT Id, Account.Name FROM Contact LIMIT 1];
String safeName = c2.Account?.Name;The first query filters out contacts without an account, so c.Account is never null. The second query makes no such guarantee. If the contact has no account, c2.Account is null, and c2.Account.Name would throw a System.NullPointerException. The safe navigation operator ?. returns null instead of throwing.
A related point: c.Account is null when the lookup is empty, but it is also an sObject that contains only the fields you selected. In the example above, c.Account.Industry would throw an SObjectException because Industry was not in the query.
Handling optional lookups
Lookup fields are often empty, so assume a parent can be missing unless the field is required. These patterns help:
- Filter in the query, as in
WHERE AccountId != null, when you only care about records with a parent. - Use
?.when reading a value, and give it a default with the null-coalescing operator. - Check the lookup ID field (
c.AccountId) before touching the parent object.
List<Contact> contacts = [SELECT Id, LastName, Account.Name FROM Contact LIMIT 20];
for (Contact c : contacts) {
String label = c.Account?.Name ?? 'No account';
System.debug(c.LastName + ' - ' + label);
}Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `System.NullPointerException` on `c.Account.Name` | The lookup is empty | Use `c.Account?.Name` or filter with `AccountId != null` |
| `System.SObjectException: SObject row was retrieved via SOQL without querying the requested field` | The field was not in the SELECT list | Add the field, such as `Account.Industry`, to the query |
| `System.QueryException` in a loop over `a.Contacts` | The child relationship name was misspelled in the query, so it failed when run | Check the child relationship name on the lookup field definition |
| Null results on a custom parent | Using `Project__c` instead of `Project__r` for the parent object | Use the `__r` name to reach fields, and `__c` to reach the ID |
Exercise
A query selects Id, Name, (SELECT LastName FROM Contacts) from Account. One account has no contacts. What does a.Contacts return for that account, and does a.Contacts.size() throw an error?
Show answer
It returns an empty list, not null. a.Contacts.size() returns 0 and does not throw an error.
Exercise
You run SELECT Id, Account.Name FROM Contact LIMIT 1 and read c.Account.Name. The contact has no account. Which error occurs, and what is a one-line fix?
Show answer
A System.NullPointerException, because c.Account is null. Use c.Account?.Name, optionally with ?? 'No account' to supply a default.