Sub topic 11
Creating COUNT, SUM, MIN, and MAX Roll-Ups
A roll-up summary field lives on the master object of a master-detail relationship. It calculates a value from the related detail records. This chapter assumes you know how to open the Object Manager and that the detail object already has a master-detail field pointing to the master. The previous chapter covered why that relationship is required.
The four summary types
| Type | What it calculates | Field it needs on the detail object |
|---|---|---|
| COUNT | Number of detail records | None |
| SUM | Total of the values | Number, currency, or percent |
| MIN | Smallest value | Number, currency, percent, date, or date/time |
| MAX | Largest value | Number, currency, percent, date, or date/time |
SUM works only on numeric fields. MIN and MAX also accept date and date/time fields, so you can show the earliest or latest date among the child records.
Creating a roll-up
Suppose Invoice__c is the master and Line_Item__c is the detail. To total the line amounts on each invoice:
- Open Object Manager and select the master object,
Invoice__c. - Go to Fields & Relationships and click New.
- Choose Roll-Up Summary as the data type, then click Next.
- Enter the label
Total Amount. The API name becomesTotal_Amount__c. - Select the detail object,
Line_Item__c. - Choose the summary type SUM, and choose
Amount__cas the field to total. - Leave the filter on "All records", set field-level security, and save.
How the value is calculated
The result is stored on the master record. It is a real field, so you can use it in list views, reports, validation rules, and formulas. You cannot set it with DML, which is why code must re-query the record to read it:
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);Behavior to expect
- A master with no detail records returns 0 for COUNT and SUM. MIN and MAX return blank.
- Detail records with a blank value in the summarized field are skipped by SUM, MIN, and MAX.
- COUNT counts every detail record, whatever its field values.
- The roll-up changes when child records are created, edited, or deleted.
Common errors
- The Roll-Up Summary option is missing. The object is not on the master side of a master-detail relationship. A lookup relationship does not offer it.
- The field to total is not listed. The detail field has the wrong type. Choose a numeric field for SUM.
- The value in Apex looks like 0 or null. The record in memory was not refreshed after the child records changed. Query it again.
Exercise
You need to show the most recent activity date among the Line_Item__c records on each Invoice__c. Which summary type do you choose, and what must the date field's data type be?
Show answer
Choose MAX. The field must be a date or date/time field on Line_Item__c. SUM and COUNT would not return a date.