Sub topic 1
How Salesforce objects relate: lookup and master-detail
SOQL relationship queries follow links that already exist between objects. Before you write one, you need to know what those links are, how they differ, and where to find them in your org. This chapter covers the two main relationship types and how each one affects the queries you write later.
Prerequisites
This chapter assumes you have the following:
- You can read and write basic SOQL:
SELECT,FROM,WHERE,ORDER BY, andLIMIT. - You know that Salesforce stores data as objects (like tables) with fields (like columns), and that every record has a unique 15- or 18-character ID.
- You can open the Developer Console, Workbench, or VS Code with the Salesforce extensions, so you can run queries and anonymous Apex.
- For the Apex example near the end, you know basic Apex syntax. You don't need Apex for the rest of the chapter.
What a relationship is
A relationship connects records in one object to a record in another. The link is stored as a field on one side. That field holds the ID of the record on the other side. The object that holds the ID field is the child. The object whose record the ID points to is the parent.
Take a Contact that belongs to an Account. The Contact has a field named AccountId. It holds the ID of an Account record. So Contact is the child and Account is the parent.
Two points to keep in mind:
- The ID field always lives on the child. The parent has no field that lists its children. The parent finds its children by searching for child records whose ID field matches.
- One parent can have many children, but each child record points to at most one parent through a given field. This is a one-to-many relationship.
SOQL can follow the link in either direction. Going from child to parent reads fields from the record the ID points to. Going from parent to child collects the records that point back. The later chapters cover both directions in detail. Here you only need to see how the link is created and what kind it is.
Lookup relationships
A lookup relationship is the loosest link between two objects. It is a field on the child that references a record in another object. Many standard links are lookups, such as Opportunity.AccountId and Case.ContactId. You can also create lookup fields on custom objects.
A lookup has these properties:
- Optional by default. You can leave the field empty. You can also mark it required on the field definition or in a page layout.
- Independent children. A child with a lookup keeps its own owner (
OwnerId) and its own sharing. Access to the parent does not control access to the child. - Configurable delete behavior. When someone deletes the parent, you choose what happens to the lookup value. It can be cleared, or the delete can be blocked while children exist. The default is to clear the value.
- Reparenting. You can point the child at a different parent at any time.
- No roll-up summary fields. The parent cannot use the built-in roll-up summary field type to total its children. You can get the same result with a flow, Apex, or an aggregate query.
Because a lookup can be empty, a query on the child may return a record whose parent is null. Your later Apex code has to handle that case.
Master-detail relationships
A master-detail relationship ties the child tightly to its parent. Salesforce calls the parent the master and the child the detail. The detail record cannot exist without its master.
A master-detail relationship has these properties:
- Required. The master field on the detail must always have a value. You cannot save a detail record without it.
- Cascade delete. Deleting the master also deletes all its detail records. Restoring the master from the recycle bin restores them too.
- Inherited ownership and sharing. The detail record has no
OwnerIdfield of its own. It takes its owner and sharing from the master. The master's sharing and security settings control who can see and edit the detail. - Roll-up summary fields. The master can define roll-up summary fields (
COUNT,SUM,MIN,MAX) over its details. - Reparenting is off by default. After you create a detail, you can only move it to another master if you turn on "Allow reparenting" on the field.
Limits on master-detail relationships:
- A custom object can have at most two master-detail relationship fields.
- A standard object cannot be the detail side of a master-detail relationship to a custom master. Standard objects can act as the master, as in a custom object that is detail to Account.
- You can usually only create a master-detail field on a custom object that has no records yet, or you have to fill the field on every existing record first. The common workaround is to create a lookup, fill it on every record, and then convert it to master-detail.
Some standard relationships are master-detail. For example, OpportunityLineItem is a detail of Opportunity.
Comparing the two types
| Feature | Lookup | Master-detail |
|---|---|---|
| Parent value required | No (optional by default) | Yes, always |
| Child has its own `OwnerId` | Yes | No, takes the master's owner |
| Sharing and security | Separate on the child | Inherited from the master |
| Deleting the parent | Clears the value or is blocked | Deletes the children |
| Roll-up summary fields | Not available | Available on the master |
| Limit per custom object | Many | Two master-detail fields |
For SOQL, the practical effect is small. The query syntax for traversing a lookup is the same as for a master-detail. The differences show up in the data you get back:
- On a lookup, the parent can be missing. A master-detail child always has a master.
- A lookup child has an
Owneryou can select. A master-detail child has noOwnerId, so a query forOwner.Nameon it fails with an error. - Roll-up summary fields from master-detail appear as ordinary fields on the master. A lookup parent needs a subquery or an aggregate query to produce the same numbers.
Special relationship shapes
You will meet a few variations on the basic link.
Self-relationships. An object can point to itself. Account.ParentId points from one Account to another Account. A child account and its parent are both Account records.
Hierarchical relationships. This is a special lookup on the User object. It points from one User to another, such as a manager. Only User can have this type.
Many-to-many with a junction object. Salesforce has no direct many-to-many field. You build one with a junction object, which is a custom object with two master-detail fields. Each record in the junction object links one record from each master. For example, a Project_Member__c object could have master-detail fields to Project__c and to Contact. One project can have many members, and one contact can be on many projects.
Polymorphic lookups. A few fields can point to more than one object type. Event.WhatId can point to an Account, an Opportunity, or other objects. Owner fields can point to a User or a Queue. A later chapter covers these with TYPEOF.
External and indirect lookups. These link to data stored outside Salesforce. They are outside the scope of this tutorial.
Finding the relationships in your org
You should check the real relationships in your org before you write a relationship query. Names and types differ between orgs, especially on custom objects.
There are three ways to check:
- In Setup, open Object Manager, choose the object, and open Fields & Relationships. Lookup and master-detail fields show their type and the object they reference.
- Use the Schema describe methods in Apex.
- Use the Salesforce REST API describe resource or the CLI.
This anonymous Apex lists every reference field on Contact and the object each one points to:
Map<String, Schema.SObjectField> fields = Contact.SObjectType.getDescribe().fields.getMap();
for (Schema.SObjectField f : fields.values()) {
Schema.DescribeFieldResult d = f.getDescribe();
if (d.getType() == Schema.DisplayType.REFERENCE) {
System.debug(d.getName() + ' -> ' + d.getReferenceTo()
+ ' (relationship name: ' + d.getRelationshipName() + ')');
}
}Run it in the Developer Console and read the debug log. You will see fields such as AccountId, OwnerId, and ReportsToId. Each is listed with its target object and its relationship name. The relationship name is not the same as the field name. The next chapter explains why, and how to use it in queries.
A first look at both directions
Here are two short queries on the Account and Contact link. They only show that the same relationship works both ways. The details come in the chapters after this one.
SELECT Id, LastName, AccountId, Account.Name
FROM Contact
LIMIT 5This query starts at the child. AccountId is the ID field stored on the Contact. Account.Name reads a field from the parent record.
SELECT Id, Name, (SELECT Id, LastName FROM Contacts)
FROM Account
LIMIT 5This query starts at the parent. The subquery collects the child Contacts for each Account.
Both queries use the same stored link, the AccountId field on Contact. They write it differently because the name used in the query depends on the direction.
Practical effects for query design
Keep these points in mind when you plan a relationship query:
- Pick the starting object by what you want back. Start at the child when you want one row per child with some parent data. Start at the parent when you want one row per parent with its children nested inside.
- Expect empty parents on lookups. A query that filters on a parent field, such as
WHERE Account.Industry = 'Technology', excludes children whose lookup is empty. Children with no parent can never match a condition on parent fields. - Expect cascade effects in data. If a process deletes Accounts, master-detail children disappear with them, and lookup children keep their records with an empty parent value. Queries over time can return different counts for these two types.
- Check access. Querying a parent field requires read access to that parent object and field. Users without access to the parent object cannot read parent fields through the child.
<br>
Exercises
Exercise
A custom object Invoice_Line__c has a master-detail field to Invoice__c. You write SELECT Id, Owner.Name FROM Invoice_Line__c. The query fails. Why, and what would you query instead to find who is responsible for the line?
Show answer
A detail record in a master-detail relationship has no OwnerId field, so there is no Owner relationship to traverse. The owner is inherited from the master. Query through the master instead, for example SELECT Id, Invoice__r.Owner.Name FROM Invoice_Line__c, assuming the master-detail field's relationship name is Invoice__r.
Exercise
Your org has Project__c and Contact. You need each contact to be able to work on many projects, and each project to have many contacts. Which structure do you build, and which relationship type do the fields use?
Show answer
Build a junction object, such as Project_Member__c, with two master-detail fields: one to Project__c and one to Contact. Each junction record links one project to one contact. Salesforce has no direct many-to-many field.
Exercise
You run SELECT Id, Name FROM Opportunity WHERE Account.Industry = 'Technology'. Some Opportunities have no Account. Are they in the results, and why?
Show answer
No. AccountId is an optional lookup, and an Opportunity with an empty value has no parent record to test. The condition on Account.Industry cannot be true for it, so it is excluded.