Sub topic 3
Child-to-parent: selecting parent fields with dot notation
A child-to-parent query starts from the record that holds a lookup or master-detail field and reads fields from the record that field points to. This chapter covers the syntax, how to find the right relationship name, what the results look like, and the errors that come up most often.
This chapter assumes you can write basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT), and that you know what objects, fields, and record IDs are. It also assumes you know a lookup relationship from a master-detail relationship. A few examples use Apex. You only need to read simple loops and variable assignments.
The idea in one query
Each Contact has an AccountId field. It holds the ID of the Account the contact belongs to. In this relationship the Contact is the child and the Account is the parent. To read the Account's name with each contact, you do not write a join. You follow the relationship with a dot:
SELECT Id, LastName, Account.Name
FROM ContactAccount.Name means: take this contact's parent Account and return its Name field. SOQL finds the parent through the relationship and returns the field in the same row. This is called dot notation.
The query returns one row per contact. If two contacts share an account, the account's name appears on both rows. Nothing is combined or collapsed.
Field name versus relationship name
The most common mistake in this topic is mixing up the two names. A relationship field has two names, and they do different jobs.
- The field name (for example
AccountId) holds the parent's record ID, a plain string. Use it to read or filter on the ID itself. - The relationship name (for example
Account) lets you reach the parent record's other fields. Use it with a dot.
The rules for finding the relationship name depend on whether the field is standard or custom.
- For a standard field, drop the
Idat the end.AccountIdbecomesAccount.OwnerIdbecomesOwner.CreatedByIdbecomesCreatedBy. - For a custom field, replace
__cwith__r.Project__cbecomesProject__r.
| Child object | Lookup field | Relationship name | Example path |
|---|---|---|---|
| Contact | `AccountId` | `Account` | `Account.Name` |
| Opportunity | `AccountId` | `Account` | `Account.Industry` |
| Account | `OwnerId` | `Owner` | `Owner.Name` |
| Case | `ContactId` | `Contact` | `Contact.Email` |
| Task__c (custom) | `Project__c` | `Project__r` | `Project__r.Name` |
For custom fields, the relationship name is set when the field is created. Salesforce proposes the field name without the __c suffix, and an admin can change it. A field called Project__c therefore normally has the relationship name Project__r, but you should confirm it. To check a custom field, look at its Child Relationship Name in the object's field details in Setup, or in the object's describe result. The describe result lists each reference field's relationshipName.
The next two queries show a correct and an incorrect way to read a parent name:
-- Correct: traverse the relationship name
SELECT Id, Account.Name FROM Contact
-- Wrong: AccountId is a string ID, so it has no sub-fields
SELECT Id, AccountId.Name FROM ContactThe second query fails with an error such as No such column 'Name' on entity 'Contact' or a similar relationship error. If you see an error about a missing relationship, check the name first. Typos and a missing __r account for most of these errors.
Selecting parent fields
You can mix child fields and parent fields in the same SELECT list. You can also select several fields from the same parent:
SELECT Id, LastName, Email, Account.Name, Account.Industry, Account.AnnualRevenue
FROM ContactEach Account. path is a separate field in the list. SOQL does not support a wildcard such as Account.*, and FIELDS(ALL) does not expand parent fields. Name each parent field you need.
The parent's ID is available two ways. AccountId is a field on the contact. Account.Id is a field on the parent record. They have the same value, and the first one costs nothing extra to select. Use Account.Id only when you want the ID inside the nested parent record.
A longer example
This query reads fields from the parent Account and from the Account's owner. It also filters and sorts on a parent field:
SELECT Id, LastName, Account.Name, Account.Owner.Name
FROM Contact
WHERE Account.Industry = 'Technology'
ORDER BY Account.NameThe query has four parts:
Account.Namereads the parent account's name.Account.Owner.Namegoes up a second level. It reads the Account's owner and then that user'sName. The next chapters cover multi-level paths in more detail.WHERE Account.Industry = 'Technology'filters contacts by a field on the parent. The parent field does not have to appear in theSELECTlist.ORDER BY Account.Namesorts the contacts by their parent's name.
You can write parent paths in the SELECT, WHERE, and ORDER BY clauses. You can also use them in GROUP BY, which a later chapter covers.
Custom objects
Custom objects work the same way. Only the suffix changes. Suppose Task__c has a lookup field Project__c that points to Project__c:
SELECT Id, Name, Project__r.Name
FROM Task__c
WHERE Project__r.Status__c = 'Active'The path uses Project__r for the relationship. The fields after the dot use their own API names. Name is a standard field, so it has no suffix. Status__c is a custom field on the parent, so it keeps its __c. Only the relationship segment switches from __c to __r.
A custom relationship name can hide a trap. In Project__r.Status__c, the part before the dot is the relationship name, and the part after the dot is a field name. Do not write Project__c.Status__c.
What the result looks like
A query that includes Account.Name returns each contact as a record with a nested Account record. In Apex, you read the parent through the relationship name:
Contact c = [SELECT Id, Account.Name FROM Contact WHERE AccountId != null LIMIT 1];
String accountName = c.Account.Name;
System.debug(accountName);The parent record is part of the contact object. It holds only the fields you selected. If you select Account.Name, then c.Account.Name works. Reading c.Account.Industry without selecting it throws a System.SObjectException, with a message like SObject row was retrieved via SOQL without querying the requested field.
When the parent is empty
A lookup field can be empty. A contact without an account has a null AccountId. The query still returns the contact, and the parent fields come back as null. SOQL does not drop the row. The query behaves like a left outer join.
Reading through a null parent in Apex causes a null-reference error. The first lines below fail on a contact with no account. The last line is safe:
Contact c2 = [SELECT Id, Account.Name FROM Contact LIMIT 1];
// Throws System.NullPointerException if c2 has no Account
// String name = c2.Account.Name;
// Safe navigation returns null instead of throwing
String safeName = c2.Account?.Name;
System.debug(safeName);The ?. operator is safe navigation. If the value on its left is null, the whole expression evaluates to null. Use it whenever the lookup can be empty. A later chapter covers result handling in Apex in full.
Master-detail fields are different. The parent is required, so the relationship is never empty on saved records. A master-detail field still needs the correct relationship name in the query.
If you only want contacts that do have a parent, add a filter on the ID field:
SELECT Id, LastName, Account.Name
FROM Contact
WHERE AccountId != nullPolymorphic fields
Some lookup fields can point to more than one object type. OwnerId on many objects can reference a User or a Queue. Paths such as Owner.Name still work, because both types have a Name field. If you need a field that exists on only one type, such as Owner.Email, a filter on Owner.Type or a TYPEOF clause is needed. A later chapter covers TYPEOF.
Limits to know about
- A single query can include at most 55 child-to-parent relationships. A path like
Account.Owner.Namegoes up two levels. - A path can go up at most five levels from the starting object.
- Each query returns the rows of one object. The parent data is attached to those rows. You cannot use this syntax to add parent rows as separate results.
These limits are enough for most queries. Check the current SOQL limits in the Salesforce documentation if you build wide queries.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `No such column 'Project__c.Name'` or a relationship error on a custom field | Used the `__c` field name instead of the `__r` relationship name | Use `Project__r.Name` |
| `No such column 'AccountId.Name'` | Put a dot after the ID field | Use `Account.Name` |
| `Invalid field` after a typo in the relationship | The relationship name differs from the field name, for example a renamed custom relationship | Check the Child Relationship Name or the describe result |
| `NullPointerException` in Apex | The lookup was empty and the code read through it | Use `?.` or check for null first |
| `SObjectException` in Apex | The parent field was not in the `SELECT` list | Select the field and re-run the query |
Summary of the pattern
- Find the lookup or master-detail field on the child object.
- Turn the field name into a relationship name: drop
Idfor standard fields, change__cto__rfor custom fields. - Write
RelationshipName.FieldNameanywhere you would write a field. - In Apex, read the same path from the returned record, and guard against a missing parent.
Exercise
A custom object Invoice_c has a lookup field Customerc that points to Account. Its relationship name is Customer_r. Write a query that returns each invoice's Id and Name together with the customer's name and industry, only for invoices whose customer has the industry 'Retail', sorted by the customer's name.
Show answer
SELECT Id, Name, Customer_r.Name, Customerr.Industry FROM Invoicec WHERE Customerr.Industry = 'Retail' ORDER BY Customer_r.Name
Exercise
A query reads SELECT Id, AccountId.Name FROM Contact and fails. Explain why, and give the corrected query. Also say what value Account.Name has for a contact with no account.
Show answer
AccountId is the field that holds the parent's ID, which is a string, so it has no sub-fields. The path must use the relationship name Account. The corrected query is SELECT Id, Account.Name FROM Contact. For a contact with no account, the row is still returned and Account.Name is null.