Sub topic 16
Aggregating child records on lookup relationships
This chapter assumes you know the difference between lookup and master-detail relationships, can create custom fields in Object Manager, and can read basic Apex.
Why lookups have no roll-up summary field
A roll-up summary field needs a master-detail relationship. In a lookup relationship, the child record is independent of the parent. It can exist without a parent, and it doesn't inherit the parent's sharing or deletion behavior. Salesforce can't guarantee a reliable aggregate in that setup, so the Roll-Up Summary option doesn't appear on the parent object.
You have three ways to get the same result:
| Option | Effort | Best when |
|---|---|---|
| Convert the lookup to master-detail | Low | Every child always has a parent, and master-detail behavior is acceptable |
| Record-triggered Flow | Medium | The logic is simple and an admin should maintain it |
| Apex trigger with aggregate query | High | Volume is high, or the logic is complex |
Converting needs every existing child record to have a parent value first. It also changes sharing and deletion: the child inherits the parent's sharing, and deleting the parent deletes its children.
How a manual roll-up works
All manual approaches follow one pattern.
- Watch for inserts, updates, deletes, and undeletes on the child object.
- Collect the parent IDs affected.
- Aggregate the children for those parents.
- Write the result to a regular field on the parent.
The target is a normal number or currency field. Unlike a roll-up summary field, you must keep it correct yourself.
An Apex example
This method totals Payment__c records for each account and writes the sum to Total_Payments__c.
public static void recalculateTotals(Set<Id> accountIds) {
Map<Id, Account> toUpdate = new Map<Id, Account>();
for (Id accId : accountIds) {
toUpdate.put(accId, new Account(Id = accId, Total_Payments__c = 0));
}
for (AggregateResult ar : [
SELECT Account__c acct, SUM(Amount__c) total
FROM Payment__c
WHERE Account__c IN :accountIds
GROUP BY Account__c
]) {
Id accId = (Id) ar.get('acct');
toUpdate.get(accId).Total_Payments__c = (Decimal) ar.get('total');
}
update toUpdate.values();
}Two details matter here. The map is pre-filled with zero for every affected parent. An account whose last payment was deleted returns no row from the aggregate query, so without the default it would keep a stale total. The query also groups by the lookup field and filters with a bind variable, which keeps it to one query for all parents.
Common errors
- Handling only inserts. Updates that change the lookup field, deletes, and undeletes all change totals. On a reparent, recalculate both the old and new parent.
- Querying inside a loop. Run one aggregate query per batch of parent IDs, not one per parent.
- Forgetting the null case. A parent with no children yields no aggregate row.
- Expecting instant consistency across transactions. Concurrent updates to the same parent can conflict, so test with bulk loads.
Exercise
A Payment_c record is moved from Account A to Account B by changing its Account_c lookup. Which accounts need their totals recalculated, and why?
Show answer
Both. Account A lost a payment and Account B gained one. The trigger must read the old lookup value (Trigger.old) and the new value (Trigger.new) and pass both IDs to the recalculation method.