Sub topic 13
Formula Fields: Calculated Values That Are Not Stored by Hand
This chapter assumes you know how to create a custom field in Object Manager and that you have met the basic field types: text, number, currency, date, checkbox, and picklist. It covers what a formula field is, how to choose its return type, and the errors that show up most often.
What a formula field is
A formula field holds no value that a user types. Salesforce calculates the value each time a record is read, using an expression you write once in the field definition. The result is always current. If an input changes, the formula result changes with it.
Use a formula field when the value can be derived from other data. Typical cases:
- A discounted price that comes from a list price and a discount percent.
- A flag that shows whether a record is overdue.
- A value copied from a related record, such as the owner's manager shown on a case.
- A clickable link that is built from a record Id.
If a person must be able to override the value, a formula is the wrong choice. Formula fields are read-only.
Return types
Every formula field has a return type. You choose it when you create the field, and it controls how the result is displayed and which operations you can perform on it.
| Return type | Result | Typical use |
|---|---|---|
| Checkbox | true or false | Flags such as "is overdue" |
| Currency | Money amount | Weighted amounts, discounted totals |
| Date | Calendar date | Due date computed from a start date |
| Date/Time | Date with time | Deadline from a timestamp |
| Number | Decimal number | Ratios, counts of days |
| Percent | Number shown with a % sign | Conversion rate |
| Text | String | Combined names, hyperlinks, status labels |
| Time | Time of day | Time offsets |
The expression must produce a value that matches the chosen type. An expression that returns text cannot be saved as a Number formula, and Salesforce rejects it with a syntax error.
Number, Currency, and Percent formulas also let you set the number of decimal places. As with regular numeric fields, this controls display and rounding of the result.
A worked example with a picklist
Picklist values cannot be compared with =. You must wrap the field in ISPICKVAL. The following Currency formula on Opportunity returns the amount only for won deals:
IF(ISPICKVAL(StageName, "Closed Won"), Amount, 0)ISPICKVAL(StageName, "Closed Won") returns true when the stage matches. IF then picks Amount or 0. Both branches return a number, so the Currency return type works.
For a multi-select picklist, use INCLUDES(field, "value") instead.
Referencing related records
A formula can read fields from a record that is related through a lookup or master-detail field. You write the relationship name, then a dot, then the field. This is called cross-object spanning.
Account.Owner.Manager.EmailSome limits apply:
- A formula can span up to 10 unique relationships to other objects.
- It can reach up to five levels up through parent records.
- It can only go upward, from child to parent. A formula cannot read a list of child records. For that you need a roll-up summary field or code.
Limits that affect design
Formula fields have size limits. The two that matter most are:
- The formula text can be at most 3,900 characters.
- The compiled size can be at most 5,000 bytes. Compiled size counts the expanded form of the formula, including references to other formula fields, so a short formula that calls other long formulas can still fail.
When you reach the limit, split the logic across two formula fields, or simplify the conditions. Splitting also makes each piece easier to test.
Formula fields also cannot be edited by users or set from an import. Reports and list views can show them, and you can filter on them, but they are not indexed by default. Filtering a large table on a formula field can be slow. If you need fast filtering on a derived value, consider storing it in a regular field that a flow or trigger keeps up to date.
Common errors
Blank values and null handling
A blank number is treated as zero in most formulas, but a blank text value is not the same as zero. When you build text, check for blanks with ISBLANK:
IF(ISBLANK(Phone), "No phone on file", Phone)You can set the field's blank handling option when you save a number formula. Choose "Treat blank fields as zeroes" when the math must still produce a result, or "Treat blank fields as blanks" when a missing input should give a blank result.
Dividing by zero
Dividing by zero produces an error in the field. Guard against it:
IF(Quantity__c = 0, 0, Total__c / Quantity__c)Wrong return type
If you choose Text and then try to add the result to a number, the formula fails. Convert with TEXT() to turn a number or picklist into text, and VALUE() to turn text into a number.
Comparing picklists with equals
Writing StageName = "Closed Won" fails. Use ISPICKVAL.
Deleting or changing referenced fields
You cannot delete or change the type of a field that a formula uses. Salesforce blocks the change until you remove the reference. This is one of the dependencies that makes changing a field type hard later.
How formulas show up in code
In Apex, a formula field appears in the object's describe information like any other field. Its isCalculated() method returns true. The value is available in SOQL queries, but you cannot assign to it in a DML statement.
Schema.DescribeFieldResult f = Opportunity.Amount.getDescribe();
System.debug(f.isCalculated()); // false for a normal fieldIn metadata, a formula appears as a CustomField with a formula element and a type that matches its return type.
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Won_Amount__c</fullName>
<label>Won Amount</label>
<type>Currency</type>
<precision>18</precision>
<scale>2</scale>
<formula>IF(ISPICKVAL(StageName, "Closed Won"), Amount, 0)</formula>
<formulaTreatBlanksAs>BlankAsZero</formulaTreatBlanksAs>
</CustomField>When not to use a formula
| Need | Better choice |
|---|---|
| Total of child records | Roll-up summary field (master-detail) or an aggregate query |
| Value that users sometimes override | Regular field with a default value |
| Fast filtering on a derived value | Stored field kept current by automation |
| Unique system identifier | Auto Number field |
Exercise
A Number formula field divides Total_c by Quantity_c and shows an error on some records. What causes it, and how do you fix it?
Show answer
Quantity_c is zero on those records, and dividing by zero causes an error. Wrap the division in a check: IF(Quantityc = 0, 0, Totalc / Quantity_c).
Exercise
You need a field that shows the sum of all open case counts under an Account, and the Case-to-Account link is a lookup. Can a formula do this? What are your options?
Show answer
No. A formula can only read parent data, not lists of child records. A roll-up summary field needs a master-detail relationship, so with a lookup you would use an aggregate SOQL query in code or an automation that writes the total to a regular field.