Sub topic 12
Lookup or master-detail, and many-to-many with junction objects
This chapter covers how to choose between a lookup and a master-detail relationship, and how to model many-to-many data with a junction object. It assumes you know what objects, records and fields are, and that you can create a field in Object Manager. It also assumes you have seen relationship fields in general. This chapter covers the decision itself.
Two ways to connect records
Both relationship types put a reference to a parent record on a child record. They differ in how tightly the child is bound to the parent.
- A lookup is a loose link. The child can exist without a parent, and the two records keep their own owners and sharing.
- A master-detail is a tight link. The child (the detail) cannot exist without its parent (the master). The detail inherits the master's owner and sharing.
The choice affects deletion, security, required data and which other features you can use. Switching later is possible but has conditions, so decide early.
How each type behaves
| Behavior | Lookup | Master-detail |
|---|---|---|
| Parent required on the child | Optional by default; can be made required | Always required |
| Deleting the parent | Default clears the lookup field on children; can be set to block deletion; cascade delete is available only for custom objects in some configurations | Always deletes the children too |
| Owner field on the child | Child has its own owner | No owner field; child takes the master's owner |
| Sharing and visibility | Child has its own sharing | Child inherits the master's sharing |
| Roll-up summary fields on the parent | Not available | Available |
| Reparenting the child | Allowed | Off by default; can be enabled with "Allow reparenting" |
| Undelete | Child is not restored with the parent | Deleting the master moves details to the Recycle Bin, and undeleting the master restores them |
Treat the cascade rows as a summary. Check the current Salesforce documentation for your org's exact options.
Lookup delete options
When you create a lookup, you choose what happens if the parent is deleted:
- Clear the value of this field. The child stays and its lookup becomes empty. This is not available if the lookup is required.
- Don't allow deletion of the lookup record that's part of a lookup relationship. This blocks the parent delete while children exist.
Master-detail consequences
- The detail object has no Owner field. Access to details follows the master through sharing.
- A detail record cannot be created without choosing a master.
- Deleting a master deletes all of its details.
- An object can have at most two master-detail relationships. This is what makes junction objects possible.
- Standard objects cannot be the detail side. A standard object such as Account can be a master, but a custom object must be the detail.
Making the choice
Ask these questions in order.
- Must the child always have a parent? If yes, lean toward master-detail. If the child can stand alone, use a lookup.
- Should deleting the parent remove the children? If yes, master-detail. If the children are valuable on their own, use a lookup.
- Should access follow the parent? If the child's visibility should match the parent's, master-detail fits. If the child needs its own owner or sharing, use a lookup.
- Do you need a roll-up summary field on the parent? Only master-detail supports it directly.
- Is the child a standard object, or does it already have records without parents? Then a lookup is the only option, unless you first fill in the parent data.
A common middle path is a required lookup with the delete option set to block deletion. The parent is required and protected, but the child keeps its own owner and sharing. If you also need a roll-up total, compute it in code instead (see below).
Many-to-many with a junction object
A single relationship field gives one parent per child. To let many records on one side relate to many records on the other, create a junction object. It is a custom object with two master-detail fields, one to each side.
Example: a Course can have many Students, and a Student can take many Courses. Create a custom object Enrollment_c with two master-detail fields, Coursec and Student_c. Each Enrollment record links one course to one student.
Junction behavior to know
- The first master-detail field you create becomes the primary master. The junction record takes its owner and sharing from that parent. The second is the secondary master.
- With two masters, a user needs access to both parents to see a junction record, based on the sharing setting of each relationship.
- Deleting either master deletes its junction records. Deleting a junction record removes only the link.
- If both parents are deleted and later one is undeleted, the junction record stays deleted until you handle the other parent. Check the documented behavior if this matters.
- Junction objects can hold their own fields, such as EnrolledOnc or Grade_c, which describe the link itself.
- Roll-up summary fields work on each master, so Course can count its Enrollments and Student can total credits.
- Add related lists for the junction object on both parent page layouts so users can see the links.
Preventing duplicates
Nothing stops two Enrollment records from linking the same course and student. To block that, use a unique text field populated by a flow or trigger with a combination of the two IDs, or use a duplicate rule on the junction object. Pick the approach that fits your org's tooling.
Querying relationships
From the child you can read parent fields with dot notation. From the parent you can read children with a subquery using the child relationship name.
SELECT Id, Name, (SELECT Id, Student__r.Name FROM Enrollments__r)
FROM Course__cCustom relationship names end in __r. The child relationship name for a junction defaults to the plural of the object label with __r.
Replacing a missing roll-up on a lookup
Roll-up summary fields need master-detail. If a lookup must stay, calculate the total with an aggregate query.
List<AggregateResult> totals = [
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE AccountId != null
GROUP BY AccountId
];
for (AggregateResult ar : totals) {
System.debug(ar.get('AccountId') + ': ' + ar.get('total'));
}Declarative alternatives include record-triggered flows that write totals to a field on the parent, or tools such as Declarative Lookup Rollup Summaries from the community.
Common errors
- Converting a lookup to master-detail fails. Every existing child must already have a parent. Fill in empty lookups first, then convert.
- Converting master-detail to lookup fails. Roll-up summary fields on the master block the change. Delete or replace them first.
- Choosing master-detail on a standard object as the child. This is not allowed. Use a lookup.
- Expecting sharing rules on a detail object. Details inherit access from the master, so you cannot share them separately.
- Cascade delete surprises. A user who deletes a master may remove thousands of details. Limit delete permission on masters.
Exercise
A Project__c object must track many Contractors, and each Contractor can work on many projects. You also need the number of contractors on each project. Which design do you use, and why does it allow the count?
Show answer
Create a junction object, for example Assignment_c, with two master-detail fields, one to Projectc and one to Contractor (a custom object, since a standard Contact can be a master but the junction itself is custom). Because Assignmentc is a detail of Projectc, Projectc can have a roll-up summary field of type COUNT on Assignment_c records. A lookup would not allow that roll-up.
Exercise
Invoice line records must be removed when an invoice is deleted, and they should not have their own owner. Which relationship type fits? What if you later need the invoice to be deletable only when it has no lines?
Show answer
Use master-detail from the line to the invoice, because it cascades deletes and removes the owner field. If the rule changes to "block deleting an invoice that has lines", master-detail cannot do that, since it always cascades. You would switch to a lookup with the "Don't allow deletion" option, after first removing any roll-up summary fields on the invoice.