Sub topic 5
Cascade Delete, Ownership, and Sharing in Master-Detail
This chapter assumes you can create custom objects and fields in Object Manager. It also assumes you have a master-detail field in mind, either from the earlier chapter or from your own org. It covers three behaviors that follow from the master-detail relationship: what happens to child records when the parent is deleted, who owns a child record, and who can see or change it.
The core idea: the detail record has no life of its own
In a lookup relationship, the child record is independent. It has its own owner, its own sharing, and it survives when the parent is removed. In a master-detail relationship, the child (the detail record) depends on its master record in three ways:
- Lifecycle: deleting the master deletes the details.
- Ownership: the detail has no owner of its own.
- Access: the master decides who can see and edit the detail.
All three follow from one rule: a detail record must always have a master. The master-detail field is required, and a detail record cannot exist without it.
Cascade delete
Cascade delete means a delete on the master record is applied automatically to every detail record that points to it. You don't write a trigger or a flow for this. The platform does it as part of the delete.
The cascade also continues down the hierarchy. If a detail object is itself the master of another master-detail relationship, those grandchild records are deleted too.
Cascade delete works with the recycle bin in both directions:
- Deleted details go to the Recycle Bin with the master.
- Undeleting the master restores the details that were deleted along with it.
- A detail record you deleted on its own earlier is not restored when you undelete the master.
You can see this in Apex. The example uses the Course__c, Student__c, and Enrollment__c objects from the spine, where Enrollment__c is a junction object with master-detail fields to both parents.
Course__c course = new Course__c(Name = 'Apex Basics');
Student__c student = new Student__c(Name = 'Ada Lovelace');
insert course;
insert student;
insert new Enrollment__c(Course__c = course.Id, Student__c = student.Id);
delete course;
// Normal queries no longer see the enrollment.
Integer visible = [SELECT COUNT() FROM Enrollment__c WHERE Course__c = :course.Id];
System.debug('Visible after delete: ' + visible);
// ALL ROWS includes records in the Recycle Bin.
List<Enrollment__c> binned = [
SELECT Id, IsDeleted
FROM Enrollment__c
WHERE Course__c = :course.Id
ALL ROWS
];
System.debug('In recycle bin: ' + binned.size());
undelete course;
Integer restored = [SELECT COUNT() FROM Enrollment__c WHERE Course__c = :course.Id];
System.debug('Restored after undelete: ' + restored);Run this as anonymous Apex and check the debug log. The three messages should show 0, 1, and 1.
Edge cases for cascade delete
- Junction objects have two masters. Deleting either master deletes the junction record. Deleting a
Course__cremoves its enrollments, but theStudent__crecords stay. - Other restrictions can block the cascade. If a detail record is referenced by a lookup field somewhere else that is set to "Don't allow deletion of the lookup record," the delete can fail. Plan delete behavior across the whole data model.
- Cascade is not optional. You can't turn it off on a master-detail field. If you need children to survive their parent, use a lookup.
- Bulk deletes are real deletes. A mass delete of 200 courses can remove thousands of detail records. Take this into account when you estimate the work in a transaction.
Ownership: details have no owner
A detail object has no standard Owner field. The owner of a detail record is, in effect, the owner of its master record. Three consequences follow:
- You can't set an owner on a detail record, and you can't use an owner-based assignment on it.
- If the master changes owner, the detail records follow automatically.
- Apex or SOQL that reads
OwnerIdon a detail object returns an error. Query the master's owner through the relationship instead, for exampleCourse__r.OwnerId.
The same rule explains why a detail record can't be created without a master. There would be nobody to inherit ownership from.
For a junction object, ownership and sharing follow the primary master. The later chapter on primary and secondary masters covers that distinction in full.
Sharing: the master controls access
Because a detail record has no owner, it has no sharing of its own. The organization-wide default (OWD) for a detail object is fixed at Controlled by Parent. You can't change it.
In practice:
- A user who can see the master can see its details, subject to object permissions.
- Sharing rules, manual sharing, and Apex managed sharing don't apply to the detail object. Share the master instead, and the details follow.
- Role hierarchy access works through the master's owner.
Access is the combination of two checks. The user needs object permissions on the detail object, and the user needs access to the master record.
| Action on a detail record | Needs on the detail object | Needs on the master record |
|---|---|---|
| View | Read | Read |
| Create | Create | Read, or Read/Write (see below) |
| Edit | Edit | Read, or Read/Write (see below) |
| Delete | Delete | Read, or Read/Write (see below) |
The last column depends on a setting on the master-detail field.
The "Sharing setting" on the relationship
When you create the field, you choose how much access to the master a user needs in order to create, edit, or delete detail records:
- Read/Write (the default): the user needs Read/Write access to the master. This is the stricter option.
- Read Only: a user with only Read access to the master can create, edit, and delete its details. This is less restrictive.
In metadata this is the writeRequiresMasterRead element. The values are easy to confuse. true is the less restrictive option, where Read access to the master is enough. false requires Read/Write.
<?xml version="1.0" encoding="UTF-8"?>
<!-- force-app/main/default/objects/Enrollment__c/fields/Student__c.field-meta.xml -->
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Student__c</fullName>
<label>Student</label>
<referenceTo>Student__c</referenceTo>
<relationshipLabel>Enrollments</relationshipLabel>
<relationshipName>Enrollments</relationshipName>
<relationshipOrder>1</relationshipOrder>
<reparentableMasterDetail>false</reparentableMasterDetail>
<type>MasterDetail</type>
<writeRequiresMasterRead>true</writeRequiresMasterRead>
</CustomField>This field is the secondary master (relationshipOrder 1) and lets users with Read access to a student create enrollments. Choose the stricter setting when adding a detail changes something sensitive about the master. Choose the looser one when many people need to add details to records they can only view, such as comments or enrollments.
Junction objects and sharing
A junction record has two masters, so two access checks apply. A user's access to a junction record is based on their access to both masters, together with the sharing setting on each master-detail field. If a user can see the course but not the student, they can't see that enrollment. Keep this in mind when you set OWDs on the two parent objects. Making one parent Private can hide junction records that look obviously visible from the other side.
Reparenting
By default, you can't move a detail record to a different master once it is saved. That is the reparentableMasterDetail element, which is false in the examples above. Set it to true, or tick Allow reparenting in the field's options, to let users change the master. When reparenting is allowed:
- The new master's owner becomes the effective owner.
- The sharing changes with it. The user needs access to the new master as well as to the detail.
- Roll-up summary fields on the old and new masters are recalculated.
If you leave reparenting off, a mistaken link means deleting the detail and creating a new one. That also loses its history and any other data stored on it.
Comparing with lookup
| Behavior | Lookup | Master-detail |
|---|---|---|
| Parent required | No (by default) | Always |
| Parent deleted | Field cleared, or delete blocked, as configured | Details deleted |
| Child owner | Own `OwnerId` | Inherited from master, no `OwnerId` field |
| Child sharing | Own OWD and sharing rules | Controlled by Parent only |
| Reparenting | Always allowed | Off unless enabled |
Common problems
- "Why can't I create a sharing rule for my custom object?" The object is a detail in a master-detail relationship. Create the rule on the master object.
- A user sees the master but gets "insufficient access" adding a detail. The relationship's sharing setting probably requires Read/Write on the master. Check
writeRequiresMasterRead, or share the master with more access. - A query on
OwnerIdfails for a custom object. The object is a detail. UseMaster__r.OwnerId. - A delete of a master fails unexpectedly. Look for children, or children of children, that are blocked by another relationship's delete restriction.
- A record count dropped after a delete. Cascade delete removed details. Check the Recycle Bin before assuming data loss, and use
ALL ROWSin SOQL to confirm.
Design checklist
Before choosing master-detail, ask these questions:
- Should a child ever outlive its parent? If yes, use a lookup.
- Does anyone need to own, or separately share, individual child records? If yes, use a lookup, because master-detail removes both.
- Could a single parent hold enough children for a cascade delete to be a problem in one transaction?
- Should users who can only view the master be able to add details?
- Will you ever need to move a detail record to another master? If so, enable reparenting when you create the field.
Exercise
A user has Read-only access to a Course_c record and Create permission on Enrollmentc. The Coursec field on Enrollment_c is a master-detail field with the default sharing setting (Read/Write required on the master). Can the user create an enrollment for that course? What single change to the field would let them, and what is the metadata value?
Show answer
No. The default setting requires Read/Write access to the master, and the user only has Read. Changing the field's sharing setting to the less restrictive option, where Read access to the master is enough, would allow it. In metadata, set writeRequiresMasterRead to true.
Exercise
You delete a Course_c record that has 50 Enrollmentc junction records, then realize it was a mistake. The Student_c records still exist. What is the state of the enrollments, how can you confirm it in SOQL, and how do you get everything back?
Show answer
The 50 enrollments were deleted with the course and are in the Recycle Bin. A normal query returns none of them, but a query with ALL ROWS returns them with IsDeleted = true. Undeleting the Course__c record restores the course and the enrollments that were deleted with it. The students were never affected, because deleting one master of a junction object removes the junction records but not the other master.