Sub topic 15
Using roll-up values inside formulas
This chapter assumes you can create a master-detail relationship, build a basic roll-up summary field, and write a formula with IF and BLANKVALUE. A roll-up summary field gives a master record a stored number. A formula field can read that number like any other field on the record. Together they let you build averages, percentages, and status flags that Salesforce does not offer as roll-up types.
Why combine them
Roll-up summary fields support only four summary types: COUNT, SUM, MIN, and MAX. There is no AVG type. There is also no way to compare two roll-ups or to turn a roll-up into a label. A formula field on the master object fills those gaps.
The two field types do different jobs:
| Field type | What it does | Where its value comes from |
|---|---|---|
| Roll-up summary | Aggregates child records | Detail records in a master-detail relationship |
| Formula | Computes a read-only result | Fields on the same record, related records, and other calculated fields |
A common pattern is to build the aggregates as roll-ups and then write one formula that combines them.
Example: average line item amount
Suppose Invoice__c is the master object and Line_Item__c is the detail object. You have two roll-up summary fields on Invoice__c:
Total_Amount__c: a SUM ofLine_Item__c.Amount__c.Line_Item_Count__c: a COUNT of line items.
Create a Number formula field on Invoice__c named Average_Line_Item__c:
IF(Line_Item_Count__c = 0, 0, Total_Amount__c / Line_Item_Count__c)The IF test matters. An invoice with no line items has a count of 0. Without the guard, the division would raise a "Divide by zero" error in the formula. The guard returns 0 in that case.
Choosing the result for an empty master
Returning 0 is a decision, and it is not always the right one. An average of 0 is different from "no data." If a report would mislead people by showing 0, you have two options:
- Return
NULLfor a Number formula. Salesforce accepts this only when you check the "Treat blank fields as blanks" option, which is the default for new formulas. The field then displays as empty. - Keep 0 and document that it means "no line items."
Pick one convention and use it across the org so users learn what an empty value means.
How roll-up values behave in formulas
Three behaviors cause most of the confusion.
- A roll-up with no children evaluates to 0 or blank. COUNT and SUM return 0 when there are no matching detail records. MIN and MAX have no value to return, so they are blank. A formula that uses MIN or MAX should handle the blank case.
- Formulas read the stored roll-up value. The roll-up is recalculated when detail records change, and the formula then reads the result when the master record is viewed or queried. You do not need to refresh the formula.
- A roll-up cannot read a formula. Roll-up summary fields can total a formula field on the detail object only in certain cases. A roll-up cannot summarize a formula that references another object's fields or a formula that itself depends on a roll-up. Check the field picker. Fields that cannot be summarized do not appear.
The first behavior is why the null-handling techniques from earlier chapters still apply. Use BLANKVALUE or ISBLANK on MIN and MAX roll-ups:
BLANKVALUE(Earliest_Due_Date__c, TODAY())This example assumes a Date roll-up named Earliest_Due_Date__c, a MIN of a date field on the detail object. If there are no line items, the formula falls back to today's date.
Example: percentage of billable items
Roll-ups can have filters. Suppose you add a second COUNT roll-up, Billable_Count__c, that counts only line items where Is_Billable__c equals True. The unfiltered count stays in Line_Item_Count__c. A Percent formula field can then compare them:
IF(Line_Item_Count__c = 0, 0, Billable_Count__c / Line_Item_Count__c)Set the formula's return type to Percent. Salesforce multiplies the value by 100 for display, so 0.75 shows as 75%.
Filters belong in the roll-up, not in the formula. A formula on the master cannot look at individual detail records. It only sees the aggregates the roll-ups already computed.
Example: a status label from a roll-up
A formula can turn a number into text, which is often more useful to users on a page layout:
IF(Line_Item_Count__c = 0, "Empty",
IF(Total_Amount__c > 10000, "High value", "Standard"))This is a Text formula. Both branches return text, which is required. Mixing a text branch and a number branch causes a syntax error.
Reading the result in code
Both field types are calculated by the platform, so Apex cannot assign to them. If you insert a record and then need the formula result, query it again:
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);The in-memory inv object does not contain calculated values. The same rule applies after you insert line items. The invoice you hold in a variable still has the old roll-up values until you query it again.
Limits to keep in mind
- Formula size. A formula has a compiled size limit of 5,000 bytes and a source limit of 3,900 characters. Long chains of nested IF statements around several roll-ups can reach these limits.
- Roll-up count. An object can have a maximum of 25 roll-up summary fields. If you create roll-ups only to feed one formula, consider whether you can reduce the number.
- Cross-object references. A formula can span up to 10 unique relationships. Roll-up values on the master object count as local fields and do not add to this.
- Formulas that reference roll-ups. Salesforce does not let a roll-up summary field summarize another roll-up in a chain. Each roll-up works from detail fields only.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "Divide by zero" error in the formula | The count roll-up is 0 and the formula divides by it | Wrap the division in an IF test |
| Syntax error about mismatched types | IF branches return different data types | Make every branch return the same type, using TEXT where needed |
| Formula shows an old value in Apex | The record variable was not re-queried | Query the record after the DML statement |
| Roll-up field missing in the formula editor | You are on the detail object, or the roll-up is on a different object | Write the formula on the master object |
| MIN or MAX result looks wrong when empty | The roll-up is blank, and the formula treats it as a number | Use BLANKVALUE or ISBLANK |
When a formula is not enough
If you need an average weighted by another field, a calculation across a lookup relationship, or logic that depends on individual detail records, a formula on the master cannot do it. Those cases need Flow or Apex, which later chapters cover.
Exercise
An Order_c master object has a SUM roll-up named TotalCost_c and a COUNT roll-up named ItemCount__c. Write a Number formula for the average cost per item that does not fail on orders with no items. Why can't you instead create this as a roll-up summary field?
Show answer
Use IF(ItemCountc = 0, 0, TotalCost_c / ItemCount__c). The IF test stops division by zero when an order has no items. A roll-up summary field cannot do this because it supports only COUNT, SUM, MIN, and MAX, so there is no AVG type.
Exercise
You insert an Invoice_c record in Apex, then insert three LineItem_c records for it. Reading TotalAmount_c from your original Invoice_c variable returns null. Why, and what should you do?
Show answer
Roll-up and formula values are calculated by the platform, not stored on the in-memory object. Query the invoice again with SOQL after the line items are inserted, and read TotalAmount_c from the query result.