Sub topic 6
Summarizing child records with roll-up summary fields
A roll-up summary field is a field on a master record that calculates a value from its detail records. It counts them, adds up a number, or finds the smallest or largest value. This chapter covers how to define one, what it can and cannot summarize, how it recalculates, and what to do for a lookup relationship, which does not support roll-ups natively.
This chapter assumes you can already create a master-detail relationship and read the cascade and sharing behavior from the previous chapter. You should also be able to read a basic SOQL query.
What a roll-up summary field is
A roll-up summary field lives on the master (parent) object of a master-detail relationship. It reads the detail (child) records that point to that master and produces one value.
Three facts define the feature:
- The field is read-only. You cannot type a value into it or set it in Apex.
- Salesforce calculates it. You do not write a trigger or a flow to keep it current.
- It requires master-detail. A plain lookup relationship does not offer the roll-up summary field type on the parent.
For example, an Invoice__c master with many Line_Item__c details can store Total_Amount__c on the invoice. Salesforce adds up the line item amounts for you.
Supported roll-up types
When you create the field you choose one of four operations.
| Operation | What it returns | Fields it can summarize |
|---|---|---|
| COUNT | Number of detail records | None. It counts records, not field values. |
| SUM | Total of a field across detail records | Number, currency, and percent fields |
| MIN | Smallest value | Number, currency, percent, date, and date/time fields |
| MAX | Largest value | Number, currency, percent, date, and date/time fields |
Two details matter in practice:
- SUM works only on numeric types. To total a duration stored as text, you must first change the storage type.
- MIN and MAX on a date field are useful for "first order date" and "most recent activity date" fields on the master.
The roll-up field's own data type follows the summarized field. A SUM of a currency field gives a currency value, and a COUNT gives a number.
Creating a roll-up summary field
In Setup, open Object Manager, choose the master object, and go to Fields & Relationships. Click New and choose Roll-Up Summary. The wizard then asks for:
- The field label and name.
- The detail object to summarize. Only objects with a master-detail relationship to this object appear in the list.
- The roll-up type, and the field to summarize for SUM, MIN, or MAX.
- Optional filter criteria, which are described below.
You can also deploy the field as metadata. This example defines a SUM of Amount__c across the line items of an invoice:
<?xml version="1.0" encoding="UTF-8"?>
<!-- force-app/main/default/objects/Invoice__c/fields/Total_Amount__c.field-meta.xml -->
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Total_Amount__c</fullName>
<label>Total Amount</label>
<summarizedField>Line_Item__c.Amount__c</summarizedField>
<summaryForeignKey>Line_Item__c.Invoice__c</summaryForeignKey>
<summaryOperation>sum</summaryOperation>
<type>Summary</type>
</CustomField>The summaryForeignKey element names the master-detail field on the detail object. If a detail object has two master-detail fields (a junction object), this element is how you choose which master the roll-up belongs to.
A COUNT field uses the same structure but omits summarizedField:
<?xml version="1.0" encoding="UTF-8"?>
<!-- force-app/main/default/objects/Invoice__c/fields/Line_Item_Count__c.field-meta.xml -->
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Line_Item_Count__c</fullName>
<label>Line Item Count</label>
<summaryForeignKey>Line_Item__c.Invoice__c</summaryForeignKey>
<summaryOperation>count</summaryOperation>
<type>Summary</type>
</CustomField>Filtering which records are summarized
By default, a roll-up includes every detail record. The wizard lets you choose Only records meeting certain criteria should be included in the calculation instead. You then define one or more conditions on fields of the detail object, such as Status__c equals Approved.
In metadata, a condition is a summaryFilterItems element inside the field definition:
<?xml version="1.0" encoding="UTF-8"?>
<!-- force-app/main/default/objects/Invoice__c/fields/Approved_Amount__c.field-meta.xml -->
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Approved_Amount__c</fullName>
<label>Approved Amount</label>
<summarizedField>Line_Item__c.Amount__c</summarizedField>
<summaryFilterItems>
<field>Line_Item__c.Status__c</field>
<operation>equals</operation>
<value>Approved</value>
</summaryFilterItems>
<summaryForeignKey>Line_Item__c.Invoice__c</summaryForeignKey>
<summaryOperation>sum</summaryOperation>
<type>Summary</type>
</CustomField>Filters let you keep several roll-ups on one master, for example total amount, approved amount, and open count. Each one counts against the per-object limit on roll-up summary fields. The default is 25 per object, so plan the number of filtered variants.
A filter is evaluated per detail record. When a detail record's Status__c changes from Draft to Approved, it enters the approved total on the next recalculation. When it changes back, it leaves.
When the value is recalculated
Salesforce recalculates a roll-up when a detail record is inserted, updated, or deleted, and when a detail record is undeleted. The change to the master is saved at that point, so the new total is visible right after the save finishes.
Several behaviors are worth knowing:
- Detail records in the Recycle Bin are not counted. Undeleting them adds them back.
- Reparenting a detail record (when the field allows it) updates both the old and the new master.
- Changing the roll-up definition (the filter, the summarized field, or the operation) does not always recalculate existing data right away. After a definition change, use Mass Recalculate Roll-Up Summary Fields on the field's detail page to recalculate every master record.
- The recalculation runs on the master as a system step. It is not a normal update you can intercept. Do not build logic that depends on a trigger firing on the master only because a roll-up changed.
Using roll-up values elsewhere
Because a roll-up summary field is a normal field on the master, you can use it in many places:
- Formula fields on the master, for example a balance equal to
Total_Amount__c - Paid_Amount__c. - Validation rules on the master, for example blocking an invoice from closing when
Line_Item_Count__cequals 0. - Page layouts, list views, and reports.
- SOQL, as with any other field:
SELECT Name, Total_Amount__c, Line_Item_Count__c
FROM Invoice__c
WHERE Total_Amount__c > 1000A roll-up summary field can also be summarized by another roll-up on a higher master in some designs, but that is limited, and a roll-up cannot reference some kinds of formula fields. If the summarized field is a formula, check the restrictions before you design around it.
Limits and edge cases
- Master-detail only. The roll-up type is not available on the master side of a lookup. This is a main reason to pick master-detail, as the comparison chapter explains.
- Dependency blocks conversion. You cannot convert a master-detail field to a lookup while a roll-up summary field depends on it. Delete the roll-up first, then convert.
- Per-object cap. A master object can hold 25 roll-up summary fields by default.
- Large data volumes. A master with a very large number of detail records can hit record locking. Many users who edit details of the same master at once can queue behind one another, because each save updates the master.
- Not directly editable. You cannot populate a roll-up with Apex or data loads. To change the value, change the detail records.
Summarizing across a lookup with Apex
A lookup relationship has no native roll-up summary field. When you need a count or total on the parent, you have several choices. One is to calculate it in a report or in a query when you need it. Another is to store it in a regular field and keep it current with a trigger or a flow. A third option, which uses code, is an aggregate query:
Set<Id> accountIds = new Set<Id>{ '001000000000001AAA' };
List<AggregateResult> totals = [
SELECT AccountId, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
];
for (AggregateResult row : totals) {
Id accountId = (Id) row.get('AccountId');
Integer total = (Integer) row.get('total');
System.debug(accountId + ' has ' + total + ' contacts');
}The Id above is a placeholder. Replace it with real account Ids before you run the code. The query returns one row per account that has at least one contact. Accounts with no contacts return no row, so treat a missing key as zero.
The trade-off is that you now own the logic. A native roll-up updates itself on every insert, update, delete, and undelete. A hand-built roll-up works only if your code covers all of those events and runs in bulk-safe form.
Common mistakes
- Looking for the Roll-Up Summary type on a lookup parent. The type does not appear because the relationship is not master-detail. Convert the relationship first, if the data allows it.
- Summarizing the wrong field type. SUM on a text field is not possible. Check that the field is numeric, currency, or percent.
- Forgetting to recalculate after a definition change. The numbers on existing masters can lag until you run the mass recalculation.
- Expecting a roll-up to fire master triggers. See the warning above.
- Overusing filtered roll-ups. A dozen near-identical fields hit the cap quickly and confuse users. Use a report for rarely needed breakdowns.
Exercise
A Project__c object has a lookup field to Account. The team wants an "Open Project Count" field on each Account that updates automatically. Why can't they create a roll-up summary field for it, and what are two ways to meet the requirement?
Show answer
A roll-up summary field can be created only on the master side of a master-detail relationship, and a lookup does not offer it. They can convert the lookup to master-detail, if the data allows it. Every Project_c record must have an Account, and the conversion must not be blocked by other conditions. Then they can create a COUNT roll-up with a filter such as Status_c not equal to Closed. If they must keep the lookup, they can store the count in a regular number field and maintain it with a trigger or flow, or they can compute it with an aggregate SOQL query when it is needed.
Exercise
An Invoice_c master has a roll-up summary field TotalAmount_c that sums LineItem_c.Amountc. A line item with an amount of 200 is deleted and goes to the Recycle Bin. The total drops by 200. The user then undeletes the line item. What happens to TotalAmount__c, and what should you do after changing the roll-up's filter criteria on an existing org?
Show answer
Undeleting the line item adds its 200 back to TotalAmountc, because Salesforce recalculates the roll-up on undelete. After changing the filter criteria, run Mass Recalculate Roll-Up Summary Fields from the field's detail page. That makes sure every existing Invoice_c is recalculated with the new definition.