Sub topic 2
Relationship names: __r suffixes and plural child names
This chapter assumes you can write basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT). It also assumes you know that a lookup or master-detail field stores the ID of a parent record. Later chapters use these names in full queries. Here the goal is to get the names right, because most relationship query errors come from a wrong name.
Two names for one relationship
A relationship between two objects has two sides:
- The child object holds a relationship field, such as
Contact.AccountId. The field stores the parent's record ID. - The parent object can list its children, such as the contacts of an account.
SOQL gives each side its own name:
| Side | What you name | Example (standard) | Example (custom) |
|---|---|---|---|
| Child record pointing to its parent | Relationship name | `Account` | `Project__r` |
| Parent record listing its children | Child relationship name | `Contacts` | `Tasks__r` |
The field name (AccountId, Project__c) holds the ID. The relationship name is what you use to move across to the other record. SOQL does not accept the field name where it expects a relationship name, and it does not accept a relationship name where it expects the ID.
Naming rules for standard relationships
For a standard relationship field, the relationship name is the field name without the trailing Id.
| Field on the child | Relationship name | Used in a query as |
|---|---|---|
| `Contact.AccountId` | `Account` | `Account.Name` |
| `Opportunity.AccountId` | `Account` | `Account.Industry` |
| `Account.OwnerId` | `Owner` | `Owner.Name` |
| `Account.ParentId` | `Parent` | `Parent.Name` |
| `Case.ContactId` | `Contact` | `Contact.Email` |
| `Opportunity.CreatedById` | `CreatedBy` | `CreatedBy.Name` |
The child relationship name is the plural form Salesforce defines on the parent: Contacts, Opportunities, Cases. It is not derived from the field name, so you cannot infer it. For example, Contact.AccountId produces Account.Contacts, but you only know this from the object reference or from a describe call (shown below).
Names are case-insensitive, so account.name and Account.Name behave the same. Use the canonical casing anyway, so queries are easy to search.
Naming rules for custom relationships
Custom relationship fields end in __c. Their relationship names end in __r. The r stands for "relationship."
- A lookup field
Project__conTask__chas the relationship nameProject__r. - The child relationship name is entered by the admin when the field is created, in the Child Relationship Name box. If the admin enters
Tasks, queries useTasks__r.
Both examples below come from the same relationship.
SELECT Id, Name, Project__r.Name
FROM Task__c
WHERE Project__r.Status__c = 'Active'SELECT Id, Name,
(SELECT Id, Name FROM Tasks__r)
FROM Project__cThe first query starts at the child and reaches the parent through Project__r. The second starts at the parent and lists children through Tasks__r.
A custom field can also point at a standard object, or a standard object can be the parent of a custom child. The suffix rule depends on the field, not on the object:
- A custom lookup field named
Region__conContacthas the relationship nameRegion__r, even thoughContactis standard. - A custom object
Invoice__cwith a standard lookup toAccountusesAccountas the relationship name, with no suffix. Its custom fieldAccount__c, if you create one, would useAccount__r. - A child relationship from a custom child to a standard parent, such as
AccounttoInvoice__c, is named by the admin and gets__r, for exampleInvoices__r.
Where the names come from
Do not guess child relationship names. Look them up with one of these.
- Object Manager. Open the child object, then Fields & Relationships, then the relationship field. The field detail page shows the field name and the Child Relationship Name. For the parent side, the API name of the field is
Project__c, and the relationship name is that name with__creplaced by__r. - Object Reference. The Salesforce Object Reference lists the child relationships for each standard object.
- Apex describe. Ask Salesforce directly. This works for standard and custom objects and always matches the org you are in.
To get the relationship name from a field:
Schema.DescribeFieldResult accountField = Contact.AccountId.getDescribe();
System.debug(accountField.getRelationshipName()); // Account
Schema.DescribeFieldResult projectField = Task__c.Project__c.getDescribe();
System.debug(projectField.getRelationshipName()); // Project__rTo list every child relationship name on a parent:
for (Schema.ChildRelationship cr : Account.SObjectType.getDescribe().getChildRelationships()) {
if (cr.getRelationshipName() != null) {
System.debug(cr.getRelationshipName() + ' <- ' + cr.getChildSObject() + '.' + cr.getField());
}
}Some child relationships have a null name because they cannot be queried as subqueries. The if skips those. The line Contacts <- Contact.AccountId in the debug log confirms that Contacts is the name to use in a subquery from Account.
Multiple relationships to the same parent
An object can have several relationship fields pointing at the same parent. For example, a custom Order__c object might have BillingAccount__c and ShippingAccount__c, both lookups to Account. Each field has its own relationship name (BillingAccount__r and ShippingAccount__r), so you pick the one you want:
SELECT Id, BillingAccount__r.Name, ShippingAccount__r.Name
FROM Order__cOn the parent side, each relationship needs a distinct child relationship name, such as BillingOrders__r and ShippingOrders__r. Salesforce enforces uniqueness of the child relationship name on a given parent object. This is why the child name is a separate setting and not derived from the field name.
Common naming errors
| What you wrote | Why it fails | Fix |
|---|---|---|
| `SELECT Project__c.Name FROM Task__c` | `Project__c` is the ID field, not a relationship | `Project__r.Name` |
| `SELECT Account__r.Name FROM Contact` | The standard relationship has no suffix | `Account.Name` |
| `SELECT (SELECT Id FROM Contact) FROM Account` | The subquery needs the plural child relationship name, not the object name | `FROM Contacts` |
| `SELECT (SELECT Id FROM Tasks) FROM Project__c` | The custom child relationship name needs the suffix | `FROM Tasks__r` |
| `SELECT AccountId.Name FROM Contact` | You cannot use dot notation on an ID field | `Account.Name` |
A frequent message for a missing suffix reads: Didn't understand relationship 'Tasks' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. The message names the relationship it failed to resolve, so compare that name against the describe output.
The first row in the table is the most common mistake. The field name and the relationship name look almost identical, and the field name is valid in a SELECT list. SELECT Project__c FROM Task__c works and returns an ID. Adding .Name to it does not.
A quick checklist
Before writing a relationship query, answer these in order:
- Which object is the child, and which is the parent?
- Are you starting from the child (use the relationship name and a dot) or from the parent (use the child relationship name in a subquery)?
- Is the relationship custom? If yes, add
__r, and confirm the child relationship name in Object Manager or with describe.
Exercise
A custom lookup field Vendor__c on Purchase__c points to Account. The admin set the Child Relationship Name to Purchases. Write the field expression that reads the vendor's name from a Purchase__c query, and the subquery source name that lists purchases from an Account query.
Show answer
The relationship name is Vendor__r, so the field expression is Vendor__r.Name, as in SELECT Id, Vendor__r.Name FROM Purchase__c. The child relationship name gets the __r suffix, so the subquery is (SELECT Id FROM Purchases__r), as in SELECT Id, (SELECT Id FROM Purchases__r) FROM Account.
Exercise
This query fails: SELECT Id, Account__r.Name FROM Contact. The Account lookup on Contact is the standard one. What is wrong, and what is the corrected query?
Show answer
Standard relationships have no __r suffix, and the relationship name is the field name AccountId without Id. The corrected query is SELECT Id, Account.Name FROM Contact.
Exercise
Write Apex that prints the relationship name of the OwnerId field on Account, and say what it prints.
Show answer
System.debug(Account.OwnerId.getDescribe().getRelationshipName()); prints Owner.