Sub topic 16
Aggregating child records on lookup relationships
Roll-up summary fields only work on master-detail relationships. This chapter covers what to do when the child object is related by a lookup. It assumes you know how master-detail and lookup relationships differ, that you can create fields in Object Manager, and that you have read the earlier chapters on roll-up limits.
Why lookups have no native roll-ups
A roll-up summary field lives on the master record. Salesforce recalculates it whenever a detail record is created, changed, or deleted. That works because a master-detail child always has a parent, and the platform controls the child's lifecycle. A lookup child can have an empty parent field. It can be reparented freely, and it can be deleted without any effect on the parent. Salesforce therefore offers no built-in roll-up on a lookup.
Your options are:
- Convert the lookup to master-detail.
- Use a record-triggered Flow.
- Use an Apex trigger.
- Use a managed or open-source roll-up package.
- Use a report, if you only need to see totals and don't need to store them.
Option 1: Convert the lookup to master-detail
This is the simplest fix, and it is often the right one. Conversion is only possible when every existing child record already has a value in the lookup field. Fill any blanks first.
Check the side effects before converting:
- The child no longer has its own owner. It inherits the sharing and ownership of the parent.
- Deleting the parent deletes the children.
- The child's parent can no longer be empty, and reparenting is allowed only if you enable it on the field.
- A parent object can have at most 40 roll-up summary fields, and a child object can have at most two master-detail relationships.
If the child needs independent sharing, or must survive deletion of the parent, conversion is the wrong choice.
Option 2: Record-triggered Flow
A record-triggered Flow on the child object can recompute the parent's total. The usual pattern is:
- Trigger the Flow after a child is created, updated, or deleted.
- Use Get Records to read the child records that share the parent.
- Loop through them and add up the amounts in a variable.
- Use Update Records to write the total to the parent.
Flow needs no code, and administrators can maintain it. Its weaknesses are the ones to watch for:
- A Flow that runs once per record and contains a query can hit governor limits during bulk loads. Keep queries and updates outside loops, and update the parent once with the computed value.
- You must handle the old parent yourself when a child is reparented. Use the prior value of the lookup field to recalculate both parents.
- Undelete is not a trigger event for Flow, so restored records need separate handling.
Option 3: Apex trigger with an aggregate query
Apex gives you full control and handles large volumes best. The pattern has two parts. A helper method recalculates totals for a set of parent IDs, and a trigger collects the affected parent IDs.
The helper uses a SOQL GROUP BY query. It starts every parent at 0, so a parent whose last child was removed is reset instead of keeping a stale value.
public with sharing class PaymentRollup {
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();
}
}The trigger must cover every event that can change a parent's total:
trigger PaymentTrigger on Payment__c (
after insert, after update, after delete, after undelete
) {
Set<Id> accountIds = new Set<Id>();
if (Trigger.new != null) {
for (Payment__c p : Trigger.new) {
if (p.Account__c != null) {
accountIds.add(p.Account__c);
}
}
}
if (Trigger.old != null) {
for (Payment__c p : Trigger.old) {
if (p.Account__c != null) {
accountIds.add(p.Account__c);
}
}
}
if (!accountIds.isEmpty()) {
PaymentRollup.recalculateTotals(accountIds);
}
}Each part handles a specific case:
Trigger.newis null on delete, andTrigger.oldis null on insert and undelete. The null checks prevent errors.- Reading both
Trigger.newandTrigger.oldcovers reparenting. The old and new parent are both recalculated. - The null check on
Account__cskips children that have no parent. - The helper takes a set, so one query and one update serve the whole batch of records.
Recalculating from scratch with an aggregate query is safer than adding or subtracting the changed amount. An incremental approach drifts out of sync if any event is missed.
Edge cases to plan for
- Record locking. Native roll-ups lock the parent while they recalculate. Your Apex update to the parent takes a lock too. Many children loaded in parallel under the same parent can cause
UNABLE_TO_LOCK_ROWerrors. Sort load files by parent, or reduce batch concurrency. - Recursion. If the parent update fires a parent trigger that updates children, you can loop. Guard against that.
- Large child sets. An aggregate query over a very large number of children can hit governor limits. Move the recalculation to Queueable or Batch Apex when you expect that.
- Existing data. A trigger only handles future changes. Run the helper once, in batches, to fill totals for existing parents.
- Validation rules and required fields. The parent update can fail if the parent has rules that the new total violates. The error then blocks the child's save.
Option 4: Roll-up packages
The open-source Declarative Lookup Rollup Summaries (DLRS) package lets administrators configure lookup roll-ups with clicks, much like the native wizard. Other packages exist on AppExchange. They save development time, but they add a dependency. You must evaluate their limits, their support, and how they behave under bulk loads.
Option 5: Reports
If users only need to see totals, a summary report grouped by the parent field is enough. It needs no field, no code, and no maintenance. A report cannot be used in a formula, a validation rule, or a field-level filter, and the value is not stored on the parent record.
Comparing the options
| Option | Stored on parent | Needs code | Best when |
|---|---|---|---|
| Convert to master-detail | Yes | No | Child can take the parent's sharing and lifecycle |
| Record-triggered Flow | Yes | No | Low to moderate volume, admin-maintained |
| Apex trigger | Yes | Yes | High volume or complex logic |
| Package such as DLRS | Yes | No | You want a configurable tool and accept a dependency |
| Report | No | No | Display only |
Reading the result
The stored total is an ordinary number field, so you can use it in formulas and queries like any other field. Because your code writes it, the value can be wrong if an event is missed. Test insert, update, reparent, delete, and undelete before you trust it.
Exercise
A Payment__c record has a lookup to Account. A user edits a payment and moves it from Account A to Account B. Why does the trigger in this chapter read both Trigger.new and Trigger.old, and what would go wrong if it read only Trigger.new?
Show answer
Trigger.new holds the new parent (Account B) and Trigger.old holds the previous parent (Account A). Reading both puts both IDs in the set, so both totals are recalculated. If the trigger read only Trigger.new, Account B would be correct, but Account A would keep a total that still included the moved payment.
Exercise
Why does the helper method set every TotalPayments_c to 0 before it applies the aggregate query results?
Show answer
A GROUP BY query returns rows only for parents that still have children. If a parent's last payment was deleted or moved, it has no row in the results. Starting at 0 resets that parent instead of leaving the old total in place.