Sub topic 1
Two ways to calculate values declaratively
Salesforce can calculate field values without code. The two main tools are formula fields and roll-up summary fields. Both give you read-only values that stay current without you maintaining them. They solve different problems and work in different ways. This chapter sets out the working model that the rest of the tutorial builds on.
Prerequisites
This chapter assumes you already have the following:
- A working knowledge of the Salesforce data model: objects, fields, and records.
- Some experience with Setup and the Object Manager, where you create custom fields.
- A high-level grasp of lookup and master-detail relationships.
- Comfort with spreadsheet-style logic, such as an
IFstatement.
You don't need to know Apex or Flow to follow this chapter. Two short code snippets appear, and both are explained.
What "declaratively" means here
A declarative calculation is one you configure in Setup instead of writing and deploying code. You describe the result you want, and the platform decides when to compute it. That has three practical benefits:
- Administrators can build and change the calculation without a deployment.
- The platform keeps the value consistent, so no trigger can forget to update it.
- Reports, list views, page layouts, and queries can all use the value like any other field.
The cost is flexibility. Declarative calculations have fixed rules about where they can read data and when they run. Knowing those rules is how you pick the right tool.
Formula fields
A formula field is a custom field whose value comes from an expression you write. The expression can use fields on the same record, fields on related parent records, operators, and functions. Here is a formula that buckets an opportunity's amount into a size label:
IF(BLANKVALUE(Amount, 0) > 100000, "Large",
IF(BLANKVALUE(Amount, 0) > 10000, "Medium", "Small"))Three properties define how formula fields behave:
- Calculated on read. The platform evaluates the expression when the value is displayed, queried, or reported. The result is not saved as ordinary field data, so it reflects the current values of the fields it reads.
- Read-only. Nobody can type a value into a formula field. The only way to change the result is to change its inputs or edit the formula.
- Typed. Every formula field has a return type, and the expression must produce that type. Common return types are Checkbox, Currency, Date, Date/Time, Number, Percent, Text, and Time.
Formulas read upward and sideways. They can see the record itself and its parents through relationship fields, such as Account.Owner.Name from an opportunity. They cannot see child records. A formula on Account can't total its opportunities, because the relationship runs from child to parent.
Roll-up summary fields
A roll-up summary field aggregates values from child records onto their parent. It is the one declarative way to look downward. A roll-up on an invoice can total the amounts of its line items. You choose one of four summary types:
| Summary type | Result |
|---|---|
| COUNT | The number of child records |
| SUM | The total of a number, currency, or percent field on the children |
| MIN | The lowest value of a number, currency, percent, date, or date/time field |
| MAX | The highest value of the same kinds of fields |
You can optionally add filter criteria so that only some children are included. A typical configuration looks like this:
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 TrueRoll-up fields differ from formula fields in several ways:
- Stored and recalculated on change. The platform saves the result on the master record. It updates that result when child records are created, edited, deleted, or undeleted. It also updates it when an edit changes whether a child meets the filter criteria.
- Dependent on master-detail. A roll-up summary field can only be created on the master side of a master-detail relationship. A lookup relationship does not qualify.
- Read-only. Like formula fields, roll-ups can't be edited by users or set by code.
Because the result is stored on the master, a roll-up can lock or contend for the master record while children are saved. A later chapter covers that behavior and the per-object limits.
Side-by-side comparison
| Question | Formula field | Roll-up summary field |
|---|---|---|
| Direction of data | Same record and parent records | Child records into the master |
| When computed | When the value is read | When child records change |
| Stored on the record | No, it is derived | Yes, the result is saved |
| Relationship required | None for same-record formulas | Master-detail |
| Operations available | Operators and functions | COUNT, SUM, MIN, MAX |
| Settable by users or code | No | No |
The "when computed" row has a visible consequence. A formula that uses TODAY() changes on its own as days pass. Nothing was edited, but the value is evaluated fresh each time. A roll-up only changes when something it depends on changes.
Choosing between them at a glance
The first question is where the data lives. The following diagram shows the first branch of that decision. A later chapter extends it to cover Flow and Apex in detail.
Two short examples show the split:
- "Show the account owner's name on an opportunity" reads upward through relationships. Use a formula field with
Account.Owner.Name. - "Show the total of billable line items on an invoice" reads downward from children. Use a roll-up summary field, provided the line items are in a master-detail relationship with the invoice.
Read-only fields in code
Neither kind of field accepts a value from DML. If Apex tries to assign one, the code won't compile or the save fails. This applies to formula and roll-up fields alike. The calculated value also isn't returned on the in-memory record after an insert. You have to query the record 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);Here Total_Amount__c is the roll-up from the earlier configuration. With no line items yet, the query returns a roll-up value of 0 for SUM. A later chapter covers formula and roll-up fields in SOQL and Apex in more detail.
When neither tool fits
Declarative calculation has boundaries. A formula can't aggregate children. A roll-up can't run on a lookup relationship, can't compute an average directly, and offers only four summary types. When a requirement falls outside those rules, you move to Flow, Apex, or a different design. The final chapters of this tutorial give criteria for that choice. Start by learning the two native tools well, because they require no code, no deployment, and no ongoing maintenance.
Exercise
A sales manager wants two new fields. The first shows the number of open cases on each account, where Case is related to Account by a standard lookup. The second shows the account's industry on each contact. Which of the two can be built with a formula field, and which cannot be built with a roll-up summary field?
Show answer
The account industry on each contact can be a formula field. A contact reads upward to its parent account, and a formula can traverse that relationship (for example Account.Industry). The open case count can't be a roll-up summary field. Roll-ups need the master side of a master-detail relationship, and Case reaches Account through a lookup. A formula can't help either, because formulas can't read child records. That requirement needs Flow, Apex, or another approach.
Exercise
Your team builds a roll-up summary field that totals billable line items on an invoice. An Apex developer inserts an invoice and then reads the roll-up field from the same in-memory variable, but the value is not what the database now holds. What should the developer do, and why?
Show answer
Re-query the record with SOQL after the insert and read the field from the query result. Roll-up and formula values are calculated by the platform, not set by DML. The in-memory record doesn't receive the calculated value, so only a fresh query returns it.