Sub topic 17
Choosing formula, roll-up, Flow, or Apex
This chapter assumes you can write basic formula fields, know how a master-detail relationship differs from a lookup, and have created a roll-up summary field. It does not introduce new syntax. It gives you a way to pick the right tool for a calculation before you build it.
Start with four questions
Most calculation requirements can be sorted by answering these questions in order.
- Where does the input data live? On the same record, on a parent record, or on child records?
- Must the result be stored, or is it enough to compute it when it is read?
- What is the relationship between the records? Master-detail or lookup?
- Does the result need to trigger something else, such as an update to another record or a notification?
The answers narrow the choice quickly.
What each tool does
| Tool | Where it computes | Stored? | Updates when | Typical use |
|---|---|---|---|---|
| Formula field | Same record, or parents reached by relationship traversal | No. Calculated when read | Every time the value is read | Labels, scores, date differences, parent values shown on a child |
| Roll-up summary field | Child records into the master | Yes | When a child is created, changed, deleted, or when the filter result changes | COUNT, SUM, MIN, MAX of children in a master-detail relationship |
| Flow | Any records the flow can query | Whatever you write to a regular field | When the flow's trigger fires | Aggregating on lookups, multi-step updates, cases that need logic beyond a formula |
| Apex | Any records | Whatever you write to a regular field | When your trigger or job runs | Large volumes, complex rules, or anything declarative tools cannot express |
A formula never writes anything to the database. A roll-up summary field is maintained by the platform. Flow and Apex write to ordinary fields, so you are responsible for keeping those values correct.
A decision path
The flowchart below turns the questions into a path. Treat it as a starting point, not a rule.
When a formula is the right choice
Use a formula when the value depends only on the record itself or on records reached through relationship traversal, and when you do not need to store the result.
IF(BLANKVALUE(Amount, 0) > 100000, "Large",
IF(BLANKVALUE(Amount, 0) > 10000, "Medium", "Small"))Strengths:
- The value is always current, because it is calculated on read.
- No automation to maintain and nothing to backfill when the logic changes.
- Cross-object formulas such as
Account.Owner.Nameshow parent data on a child without copying it.
Limits to keep in mind:
- It is read-only. You cannot set it from DML, a flow, or a form.
- It cannot look down at child records. A formula can go up through lookups and master-detail fields, never down.
- Compiled size and relationship span limits apply, so very large formulas may fail to save.
- Because the value is not stored, you cannot rely on it for every kind of reporting or filtering scenario. If you need to sort or filter at scale, check how it behaves in your queries and consider a stored field instead.
When a roll-up summary field is the right choice
Use a roll-up when you need COUNT, SUM, MIN, or MAX over child records, and the child object is the detail side of a master-detail relationship.
Master object: Invoice__c
Detail object: Line_Item__c (master-detail field Invoice__c)
Roll-up field: Total_Amount__c on Invoice__c
Summary type: SUM
Field to total: Line_Item__c.Amount__c
Filter criteria: Only records meeting criteria: Line_Item__c.Is_Billable__c EQUALS TrueStrengths:
- No code and no flow to build or test.
- The platform keeps the value correct when children change.
- Filter criteria let you total only the children you want.
Limits to keep in mind:
- It needs a master-detail relationship. A lookup does not qualify.
- Only COUNT, SUM, MIN, and MAX exist. There is no average.
- Changes to detail records lock the master record while the roll-up recalculates, which can cause lock contention when many children are loaded at once.
- Per-object limits cap how many roll-up summary fields you can create.
Average is a common case where you combine tools. Create a SUM roll-up and a COUNT roll-up, then divide them in a formula.
IF(Line_Item_Count__c = 0, 0, Total_Amount__c / Line_Item_Count__c)The guard on the count avoids a division-by-zero error on a master with no children.
When Flow is the right choice
Choose Flow when a declarative tool must do something that formulas and roll-ups cannot, and the logic is manageable without code.
- Aggregating children on a lookup relationship, where roll-up summary fields are unavailable.
- Writing a value into a regular field so you can filter, sort, report on, or use it in validation rules.
- Updating several records when one record changes.
- Sending a notification or creating a related record as part of the calculation.
Flow-based aggregation has costs. You own the logic for every event that can change the total: create, update, delete, and undelete of children, plus reparenting. You also need to bulkify carefully, because flows run inside the same governor limits as other automation. If you miss an event, the stored total drifts away from the truth, and nothing corrects it.
When Apex is the right choice
Choose Apex when volume, complexity, or control exceeds what Flow handles comfortably.
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();
}This method sets every account to zero first, then overwrites the ones that have payments. That step matters. Without it, an account whose last payment was deleted would never be updated, and its old total would remain.
Apex costs more to build and maintain. It needs tests, deployment, and a developer who can support it. Pick it when the same result in Flow would be fragile or slow.
Side-by-side scenarios
| Requirement | Best fit | Reason |
|---|---|---|
| Show the account owner's name on an Opportunity | Formula | Data is on a parent, and no storage is needed |
| Number of days until close date | Formula | Date arithmetic on the same record |
| Total of billable line items per invoice, master-detail | Roll-up with filter | COUNT, SUM, MIN, or MAX over detail records |
| Average line item amount | Two roll-ups plus a formula | No native average roll-up |
| Total payments per account, where Payment__c uses a lookup | Flow or Apex | Roll-up summary fields need master-detail |
| Total payments per account, millions of payments, frequent bulk loads | Apex | Volume and control over recalculation |
| Filterable "Large/Medium/Small" bucket in a list view | Formula, or a stored field set by Flow | Check whether the formula meets your filtering needs first |
Reading the values in code
Whichever you choose, remember that formula and roll-up fields are not writable. Code that creates a record must query it again to see the calculated values.
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 variable does not carry the calculated value after the insert. Only the re-queried record does.
Common mistakes
- Reaching for Apex for a total that a roll-up with filter criteria would handle.
- Trying to convert a lookup to master-detail only to get a roll-up, without checking that every existing child has a parent and that the cascade-delete behavior is acceptable.
- Using a formula as a stand-in for a stored field and then hitting limits when filtering or reporting on it.
- Forgetting the divide-by-zero guard when combining two roll-ups.
- Updating only the new parent when a child is reparented in a manual aggregation, so the old parent's total is never corrected.
Exercise
A Payment__c object has a lookup to Account. The business wants a field on Account that shows the sum of all payment amounts, and users must be able to filter Account list views by that total. Which tool would you pick first, and why can't you use a roll-up summary field?
Show answer
Use a record-triggered Flow first, and move to Apex if payment volume or complexity grows. A roll-up summary field needs a master-detail relationship, and Payment__c uses a lookup. A formula cannot read child records, so it cannot sum payments either. The Flow or Apex writes the total to a regular number field on Account, which users can filter on. Whichever you build, it must handle create, update, delete, undelete, and reparenting of payments.
Exercise
You need the average LineItemc amount on each Invoicec, where LineItem__c is the detail side of a master-detail relationship. How do you build it with no code, and what must the formula guard against?
Show answer
Create a SUM roll-up of Amount_c and a COUNT roll-up of line items on Invoicec, then create a Number formula field that divides the sum by the count. The formula must guard against a count of zero, for example IF(LineItemCountc = 0, 0, TotalAmount_c / LineItemCount_c), because an invoice with no line items would otherwise cause a division-by-zero error.