Sub topic 1
Relationships connect objects: parents, children, and relationship fields
Almost every Salesforce data model links records across objects. A contact belongs to an account. An opportunity belongs to an account. A custom enrollment record belongs to a course. This chapter covers the vocabulary and mechanics those links share: what a relationship field stores, how parent and child are defined, how relationship names work in queries, and the edge cases that cause confusion later. The following chapters build on this to cover lookup and master-detail behavior.
Prerequisites
This chapter assumes you already know:
- The basic Salesforce data model: standard and custom objects, fields, and records.
- How to open Setup and the Object Manager and view an object's fields.
- Basic SOQL
SELECT ... FROM ... WHEREsyntax.
You do not need to have created a relationship field before.
What a relationship is
A relationship is a link between two objects, stored as a field on one of them. The field holds the 18-character record Id of a record on the other object. That is all a relationship is at the data level: a field whose value is an Id.
Take Contact.AccountId. A contact record stores the Id of its account in this field. When you open a contact and see the account name as a clickable link, the platform looked up that Id and displayed the name of the matching account.
This has two consequences:
- The link is stored on only one side. The account record stores nothing about its contacts. The list of contacts is found by searching for contacts whose
AccountIdequals the account's Id. - The field is a real field. It can be required or optional, appear on page layouts, be used in reports and filters, and be set in code, like any other field.
Parent and child
The object that holds the relationship field is the child. The object it points to is the parent. In the Contact-to-Account example, Contact is the child and Account is the parent.
Many people get the direction wrong because the arrow in a diagram can be read either way. Use this rule: the child has the field, and the parent is the object the field references.
Salesforce documentation also uses these terms:
- Detail is another word for child, mostly used with master-detail relationships. The parent is then the master.
- Lookup and master-detail are the two main types of custom relationship field. Their differences are the subject of the next several chapters.
- Related list is how the parent's page layout shows its children. The Contacts related list on an account shows contacts whose
AccountIdis that account.
A parent can have many children, and each child record points to one parent through a given field. This is a one-to-many relationship. It is the building block for everything else, including many-to-many.
Two names for every relationship
A relationship field creates two ways to navigate, and each has its own name.
- The relationship name is used going from child to parent. For the standard field
Contact.AccountId, it isAccount. - The child relationship name is used going from parent to child. For
Contact.AccountId, viewed from the account, it isContacts.
For custom relationship fields, the API names follow a pattern.
| Item | Pattern | Example |
|---|---|---|
| Relationship field (stores the Id) | `FieldName__c` | `Course__c` |
| Relationship name (child to parent) | `FieldName__r` | `Course__r` |
| Child relationship name (parent to child) | `PluralName__r` | `Enrollments__r` |
When you create a custom relationship field in Setup, the wizard asks for a field label, a field name, and a child relationship name (called "Child Relationship Name" in the setup page). The field name drives the __r name used in child-to-parent queries. In metadata XML, the same values appear as fullName and relationshipName, without the __r suffix. Salesforce adds __r when you use the name in SOQL or Apex.
Two details trip people up:
- The
__cfield and the__rrelationship are different things.Course__cis the Id.Course__ris the parent record, and you use it to reach fields likeCourse__r.Name. - Standard relationships use no suffix, so it is
Account.Name, notAccount__r.Name.
The child relationship name must be unique among the child relationships on the parent object. If you create two lookup fields from the same child object to the same parent, you cannot give both the default plural name. Pick distinct names such as Primary_Contacts and Backup_Contacts.
Reading across a relationship in SOQL
The dot navigates from child to parent. The following query returns contacts and filters on a field of their parent account.
SELECT Id, LastName, Account.Name
FROM Contact
WHERE Account.Industry = 'Technology'Account here is the relationship name. The query reads Account.Name from the parent without a separate query, and Account.Industry in the filter. You can traverse several levels of parents in a single query (the limit is five levels), for example Contact.Account.Owner.Name.
To go the other way, use a subquery on the child relationship name.
SELECT Name, (SELECT LastName FROM Contacts)
FROM AccountHere Contacts is the child relationship name. Each returned account carries a nested list of its contacts. Accounts with no contacts still appear, with an empty list. Without a WHERE on the account, this query returns every account, so add a filter or a LIMIT for real use.
A few limits apply to these queries. A single query can include up to 55 child-to-parent relationships and up to 20 parent-to-child subqueries. Limits can change between releases, so check the current SOQL limits page before relying on exact numbers.
Reading across a relationship in Apex
The same names work on SObjects in Apex. When you query a parent field, the parent is loaded as a nested SObject.
Contact c = [
SELECT Id, LastName, Account.Name
FROM Contact
WHERE AccountId != null
LIMIT 1
];
System.debug(c.Account.Name);The WHERE AccountId != null filter matters. If a contact has no account, c.Account is null, and c.Account.Name throws a NullPointerException. When a parent may be missing, use the safe navigation operator:
String accountName = c.Account?.Name;Child records come back as a list under the child relationship name:
Account a = [
SELECT Id, Name, (SELECT LastName FROM Contacts)
FROM Account
LIMIT 1
];
for (Contact con : a.Contacts) {
System.debug(con.LastName);
}Looping over a.Contacts is safe even when the account has no contacts, because the list is empty rather than null.
A related point: the relationship data is only available if you selected it in the query. If you query SELECT Id, AccountId FROM Contact, then c.Account is null even though the contact has an account. You have the Id but did not load the parent. This is a common source of "the parent is there but the code says it is not" bugs.
Setting a relationship in code
To link a child to a parent, assign the Id to the relationship field. You do not assign the nested __r record in normal DML.
Account acct = new Account(Name = 'Acme');
insert acct;
Contact con = new Contact(LastName = 'Rivera', AccountId = acct.Id);
insert con;The parent must exist, and therefore have an Id, before you insert the child. This is why you insert the account first.
Where relationship fields appear
Several kinds of relationship exist, and it helps to recognize them even though this tutorial focuses on two.
- Lookup relationships are optional, loosely coupled links.
- Master-detail relationships are required, tightly coupled links.
- Hierarchical relationships are a special lookup available only on the User object, used for example for a manager.
- External and indirect lookup relationships connect to external data objects.
- Self-relationships are lookups from an object to itself.
Account.ParentIdpoints an account at another account. These form tree structures. - Polymorphic fields can point at more than one object type.
Task.WhoIdcan reference a contact or a lead, andTask.WhatIdcan reference an account, opportunity, or many other objects. Their relationship names (Who,What) need special handling in SOQL, such asTYPEOF.
Standard objects come with relationship fields built in, such as Contact.AccountId, Opportunity.AccountId, and Case.ContactId. Custom relationship fields add your own links.
Common mistakes
- Reversing the direction. The question to ask is "which object holds the field?" That object is the child.
- Using
__cwhere__ris needed.Course__c.Nameis invalid. UseCourse__r.Name. - Querying only the Id and expecting the parent. Select
Account.Nameexplicitly. - Assuming a child always has a parent. For optional relationships, handle
nullin Apex and expect blank values in SOQL results. - Forgetting the child relationship name is plural by default but can be changed. Check the field definition in Object Manager rather than guessing the name.
Exercise
A custom object InvoiceLinec has a relationship field Invoicec that references Invoicec. The child relationship name is InvoiceLines. Which object is the parent, and write the SOQL fragments to (a) read the invoice's Name from a line and (b) read each invoice's line Ids from an invoice query.
Show answer
Invoice_c is the parent, and InvoiceLine_c is the child because the child holds the field. (a) In a query on InvoiceLine_c, select Invoicer.Name. (b) In a query on Invoicec, use the subquery (SELECT Id FROM InvoiceLines_r). The child relationship name InvoiceLines gets the __r suffix in SOQL.
Exercise
An Apex method queries SELECT Id, AccountId FROM Contact and then reads c.Account.Name. The contact has an account, but the code throws a NullPointerException. Why, and how do you fix it?
Show answer
The query selected only the Id in AccountId, so the Account parent record was never loaded and c.Account is null. Fix it by selecting Account.Name in the query. If some contacts may have no account, also read it with the safe navigation operator, c.Account?.Name.