Sub topic 3
Summarizing Only the Records You Want
Assume you understand objects, fields, master-detail and lookup relationships, and basic formula logic. This chapter focuses on selecting child records and choosing the right calculation tool.
Filtered roll-ups
A roll-up summary field can aggregate only child records that meet filter criteria. For example, an invoice can total billable line items without including canceled items.
| Setting | Value |
|---|---|
| Summary type | SUM |
| Field to total | `Line_Item__c.Amount__c` |
| Filter | `Is_Billable__c` equals `True` |
The filter is evaluated when Salesforce recalculates the roll-up. A filter that references a changed child field can therefore change the master value.
Recalculation and locking
Roll-ups recalculate when a detail record is created, edited, deleted, or moved to another master. Salesforce may lock the master record while updating the summary. Concurrent updates can then produce record-locking errors, especially when many transactions update the same master.
Restrictions and limits
Roll-up summary fields require a master-detail relationship. They cannot directly summarize children in a lookup relationship. The available operations are COUNT, SUM, MIN, and MAX. The summarized field must have a compatible type, and each object has a platform-defined limit on roll-up summary fields. Check current Salesforce limits before designing a high-volume object.
Formulas using roll-ups
A formula can use a roll-up value as an input. Always protect divisions against an empty count.
IF(Line_Item_Count__c = 0, 0, Total_Amount__c / Line_Item_Count__c)This returns an average of zero when no line items exist.
Lookup relationships
For a lookup relationship, use Flow or Apex to perform the aggregation. Apex can group payments by account and write the result to a number field.
for (AggregateResult ar : [
SELECT Account__c accountId, SUM(Amount__c) total
FROM Payment__c
WHERE Account__c IN :accountIds
GROUP BY Account__c
]) {
Account acc = accountsToUpdate.get((Id) ar.get('accountId'));
acc.Total_Payments__c = (Decimal) ar.get('total');
}Choosing the tool
- Use a formula for a read-only value derived when the record is read.
- Use a roll-up for a supported aggregate on master-detail children.
- Use Flow for maintainable declarative updates, especially with lookup relationships.
- Use Apex for complex aggregation, large data volumes, or logic that Flow cannot express reliably.
Troubleshooting
Confirm the relationship type, filter field values, field permissions, and automation order. Test create, edit, delete, and reparent operations. Query calculated fields after DML because formulas and roll-ups cannot be assigned directly.
Exercise
Which tool fits a total of filtered child records when the relationship is lookup?
Show answer
Flow or Apex, because a standard roll-up summary requires master-detail.