Sub topic 11
Creating COUNT, SUM, MIN, and MAX roll-ups
A roll-up summary field lives on the master record of a master-detail relationship. It calculates a value from the related detail records. This chapter shows how to create one and what each summary type does. It also covers the settings that cause the most mistakes.
Prerequisites
This chapter assumes you can do the following:
- Use Setup and the Object Manager to add fields to an object.
- Describe the difference between lookup and master-detail relationships.
- Read the basic data model used in the examples:
Invoice__cis the master object andLine_Item__cis the detail object.Line_Item__chas a master-detail field namedInvoice__c.
The previous chapter explained why roll-ups need a master-detail relationship. Here the relationship already exists.
What a roll-up summary field does
A roll-up summary field is a field on the master object. Salesforce stores its value and updates it when detail records change. This differs from a formula field, which is computed each time it is read.
A roll-up has these properties:
- It is read-only. You cannot set it in the UI, in Apex DML, or through the API.
- It belongs to the master object, never the detail object.
- It summarizes direct children only. A roll-up on
Invoice__ccan summarizeLine_Item__c, but it cannot skip over a level of the hierarchy. - It returns a Number, Currency, Percent, Date, or Date/Time value, depending on the summary type and the field summarized.
The four summary types
Salesforce offers four summary types. Which ones you can choose depends on the data types of the detail object's fields.
| Summary type | What it returns | Field to aggregate | Empty result |
|---|---|---|---|
| COUNT | Number of detail records | None needed | 0 |
| SUM | Total of the field's values | Number, Currency, or Percent | 0 |
| MIN | Lowest value | Number, Currency, Percent, Date, or Date/Time | Blank |
| MAX | Highest value | Number, Currency, Percent, Date, or Date/Time | Blank |
Two details matter here:
- COUNT does not look at any field. It counts the detail records that match the filter, or all of them if you set no filter.
- MIN and MAX can return a date. For example, a MAX roll-up on a date field gives you the most recent activity date among the children.
Because MIN and MAX return a blank value when there are no detail records, a formula that uses them must handle null. A later chapter covers this.
Create a SUM roll-up step by step
This example totals the line item amounts on each invoice.
- Open Setup, then Object Manager, then
Invoice__c. - Choose Fields & Relationships, then New.
- Select Roll-Up Summary as the data type, then choose Next.
- Enter the label
Total Amount. The API name becomesTotal_Amount__c. Choose Next. - Select
Line_Item__cas the summarized object. Only objects with a master-detail relationship toInvoice__cappear in the list. - Select SUM as the roll-up type. Choose
Amount__cas the field to aggregate. - Choose the filter criteria (covered below), then choose Next.
- Set field-level security and page layout placement, then save.
The settings for a SUM that counts only billable line items look like this:
Master object: Invoice__c
Detail object: Line_Item__c (master-detail field Invoice__c)
Roll-up field: Total_Amount__c on Invoice__c
Summary type: SUM
Field to total: Line_Item__c.Amount__c
Filter criteria: Only records meeting criteria: Line_Item__c.Is_Billable__c EQUALS TrueTo create a COUNT roll-up, repeat the steps and select COUNT in step 6. You do not choose a field. For MIN and MAX, choose the field whose lowest or highest value you want.
Filter criteria
On the wizard's filter step you have two options:
- Select all records. Every detail record contributes.
- Select only records meeting certain criteria. Only matching detail records contribute.
Filters let one master object hold several roll-ups over the same children. For example, Invoice__c can have one SUM of all line items and another SUM of billable ones. The next chapter covers filters in depth.
Detail records created through Apex
Roll-up values are calculated by the platform, not by your code. If you create a master record and then read the roll-up from the same in-memory object, you get null. The in-memory object does not contain values that the platform calculates. Query the record again to read the stored result.
Invoice__c inv = new Invoice__c(Name = 'INV-001');
insert inv;
Invoice__c saved = [SELECT Id, Total_Amount__c FROM Invoice__c WHERE Id = :inv.Id];
System.debug(saved.Total_Amount__c);A newly inserted invoice with no line items returns 0 for a SUM roll-up, not null. A MIN or MAX roll-up on the same invoice would return null.
Behavior to know before you build
- Roll-ups follow the master-detail relationship. If you reparent a detail record to a different master, both masters recalculate.
- Deleting a detail record updates the master. Undeleting it adds the value back.
- Roll-ups count only records the platform can see. Calculation runs in system mode, so sharing rules and field-level security on the detail records do not change the total. A user can see a total that includes records they cannot open.
- You cannot change some settings later. After a roll-up exists, you cannot change the summarized object. If you change the summary type or the field, Salesforce warns that existing values will be recalculated.
- Dependencies can block edits. A field that a roll-up uses cannot be deleted until you remove the roll-up. Salesforce also restricts changing the data type of a field that a roll-up uses.
Where roll-ups appear
A roll-up field can appear in these places:
- Page layouts and record detail pages, when you add the field.
- Reports, as a regular field on the master object.
- List views and related lists, as a column.
- SOQL queries, as a normal field in the select list.
- Formula fields on the same master object. This is the pattern in the next sections: for example, dividing a SUM by a COUNT to get an average.
List<Invoice__c> invoices = [
SELECT Id, Name, Total_Amount__c
FROM Invoice__c
WHERE Total_Amount__c > 1000
];You can filter and sort on a roll-up field in SOQL, but you cannot write to it.
How the pieces fit together
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Roll-up summary is not offered as a data type | The object is not the master side of a master-detail relationship | Convert the lookup to master-detail, or use an alternative covered later |
| The detail object is missing from the list | No master-detail field points to this master object | Create the master-detail field first |
| Apex reads null from a roll-up after insert | The in-memory record was not refreshed | Re-query the record |
| Total looks wrong | The filter excludes records you expected | Review the filter criteria and the field values |
| Cannot delete a field | A roll-up depends on it | Remove or edit the roll-up first |
Summary
Create a roll-up on the master object and select the detail object, a summary type, and an optional filter. COUNT counts records. SUM totals a numeric field. MIN and MAX find the lowest and highest numeric or date value. Salesforce stores the result, so you read it by querying the record again after changes.
Exercise
An Invoice__c has no Line_Item__c children yet. What does each of these roll-ups return: COUNT, SUM of Amount__c, and MAX of a date field on Line_Item__c?
Show answer
COUNT returns 0, SUM returns 0, and MAX returns a blank (null) value, because there are no dates to compare.
Exercise
A developer inserts an Invoice__c and its line items in Apex, then reads inv.Total_Amount__c from the original variable and gets null. What should the developer do?
Show answer
Re-query the invoice with SOQL, for example SELECT Id, Total_Amount__c FROM Invoice__c WHERE Id = :inv.Id. The platform calculates and stores the roll-up value, so the in-memory object does not contain it.
Exercise
Which two roll-up types can summarize a Date field, and which cannot?
Show answer
MIN and MAX can summarize a Date field. SUM cannot, because dates are not totaled, and COUNT does not use a field at all.