Sub topic 14
Roll-up Summary Fields on Master-Detail Parents
This chapter covers roll-up summary fields: what they calculate, where you can create them, the limits that apply, and what to do when a relationship doesn't allow them. It assumes you know the difference between lookup and master-detail relationships from the previous chapter and can create fields in Object Manager.
What a roll-up summary field does
A roll-up summary field is a field on a parent record that calculates a value from its child records. The platform maintains it automatically. When a child record is inserted, updated, deleted or undeleted, the parent value is recalculated. Nobody types into it.
A roll-up summary field supports four operations:
| Operation | Works on | Result |
|---|---|---|
| COUNT | Child records (no field chosen) | Number of related children |
| SUM | Number, Currency, Percent fields | Total of the child field |
| MIN | Number, Currency, Percent, Date, Date/Time fields | Smallest or earliest value |
| MAX | Number, Currency, Percent, Date, Date/Time fields | Largest or latest value |
The result type follows the source. A SUM of a Currency field gives a Currency result. A MAX of a Date field gives a Date result. COUNT gives a Number.
The master-detail requirement
You can only create a roll-up summary field on the master side of a master-detail relationship. The detail object supplies the values. The master object holds the field.
A lookup relationship cannot host a roll-up summary field. This is the main reason to choose master-detail when you know the parent needs totals. Standard objects can be the master as long as the detail object is a custom object with a master-detail field pointing to them. A standard object cannot be the detail side of a new master-detail relationship to a custom object.
A junction object has two masters, so each master can have its own roll-up. For example, a junction between Project and Contractor can count assignments on both parents.
Filter criteria
By default a roll-up includes every child record. You can add filter criteria so that only matching children count. Typical filters are:
- Stage equals Closed Won
- Status not equal to Cancelled
- Expense date is this year
Filters use field values on the child records. Add them when you create the field. If you add them later, the platform needs to recalculate the existing values.
Metadata view
In metadata, a roll-up summary field has the type Summary. It names the field to summarize, the relationship field to follow and the operation. The file lives under the master object, here Project__c.
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Total_Approved_Expenses__c</fullName>
<label>Total Approved Expenses</label>
<type>Summary</type>
<summarizedField>Expense__c.Amount__c</summarizedField>
<summaryForeignKey>Expense__c.Project__c</summaryForeignKey>
<summaryOperation>sum</summaryOperation>
<summaryFilterItems>
<field>Expense__c.Status__c</field>
<operation>equals</operation>
<value>Approved</value>
</summaryFilterItems>
<precision>18</precision>
<scale>2</scale>
</CustomField>summaryForeignKey is the master-detail field on the child. If the child object has two master-detail fields, this value decides which parent the roll-up uses.
Behavior and limits
Know these points before you rely on roll-ups:
- Read-only. You can't edit the value, and you can't import it. You can read it in reports, list views, formulas and SOQL like any other field.
- Automatic recalculation. The parent updates when a child changes. Reparenting a child changes both the old and new parents.
- Per-object limit. An object can have 25 roll-up summary fields by default. Salesforce Support can raise the limit in some editions.
- Recalculation option. After you change the definition, you can choose to force a new calculation. Existing values are not always refreshed on their own.
- Locking. Many children updated at once under one parent can cause row lock errors, because every change updates the same parent row. Large data loads are best sorted by parent ID so each parent's children are processed together.
- Dependency. You can't delete or change the type of a field that a roll-up uses. Remove or edit the roll-up first.
- No lookup. You can't convert a master-detail relationship to a lookup while roll-up summary fields depend on it. Delete the roll-ups first.
When a lookup is the better relationship
Master-detail has costs. The child's owner and sharing come from the parent, the relationship field is required, and deleting the parent deletes the children. If those rules don't fit your data, keep a lookup and compute the totals another way.
| Approach | Strength | Weakness |
|---|---|---|
| Roll-up summary field | Declarative, always current | Master-detail only, 25-field limit |
| Record-triggered Flow | Works on lookup, no code | You maintain it, and bulk volume needs testing |
| Apex trigger | Full control | Code to write, test and maintain |
| Aggregate query | No stored field, good for reports or one-off logic | Computed on demand, not saved on the parent |
An aggregate query computes the same total in code:
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'));
}Aggregate results come back as AggregateResult rows. You read the alias (total) with get(), and the value is untyped, so cast it before doing arithmetic.
Reading a stored roll-up is simpler, because it behaves like an ordinary field:
SELECT Id, Name, Total_Approved_Expenses__c
FROM Project__c
WHERE Total_Approved_Expenses__c > 10000Common mistakes
- Planning a roll-up on a lookup. The option isn't offered. Decide on the relationship type before you build.
- Expecting filters to be dynamic. Filter criteria are fixed in the definition. They can't reference the running user or today's date in a way that changes.
- Forgetting the decimal places. The roll-up has its own scale setting. A SUM of two-decimal currency can display rounded if you set the scale to zero.
- Hitting the 25-field limit. If every report wish becomes a roll-up, you run out. Use reports for totals that are only needed for analysis.
Exercise
A Warranty__c object has a lookup field to Account, and the business wants Account to show the number of active warranties. A roll-up summary field isn't offered. Give two options for meeting the requirement and one consequence of each.
Show answer
Option 1: convert the lookup to master-detail, then create a COUNT roll-up with a filter on Status equals Active. Consequences: the relationship field becomes required on every warranty, warranty sharing and ownership follow the account, and deleting an account deletes its warranties. Option 2: keep the lookup and maintain a Number field on Account with a record-triggered Flow or Apex trigger, or compute the count with an aggregate query when needed. Consequence: you own the logic, so it must handle inserts, updates, deletes, undeletes and reparenting, and it must work in bulk.