Sub topic 13
Formula fields: calculated values that are not stored by hand
This chapter assumes you can create custom fields in Object Manager and know how fields relate to objects. It covers what a formula field is, how to choose its return type, and the errors that come up most often.
What a formula field is
A formula field is a read-only field whose value is calculated from other fields. Nobody types into it. Salesforce evaluates the expression whenever the record is displayed or queried, so the value always reflects the current data.
The result is not saved as editable data. If you correct a source field, every formula that uses it shows the new result immediately. This removes a common source of stale, duplicated data.
Choosing a return type
Every formula declares a return type, and the expression must produce that type. The available types are Checkbox, Currency, Date, Date/Time, Number, Percent, Text and Time.
Pick the type that matches how the result will be used. Use Currency for money so it respects the org's currency settings. Use Date when you need to sort or compare dates. Use Text only for display, because text results cannot be summed or compared numerically.
Here is a Currency formula on Opportunity:
IF(ISPICKVAL(StageName, "Closed Won"), Amount, 0)ISPICKVAL is required because a picklist value cannot be compared with =. The formula returns the amount for won deals and zero for all others.
Referencing other objects
A formula can follow a lookup or master-detail relationship to read fields from the parent record. On Opportunity, Account.Industry reads the account's industry. This is called cross-object referencing, and it works only upward, from child to parent. A formula cannot read a list of child records. Use a roll-up summary field for that.
Limits and common errors
- Size limits. A formula can hold 3,900 characters, and the compiled result must stay under 5,000 bytes. Long nested
IFstatements hit this limit. Split the logic into several formula fields, or useCASE. - Blank values. A blank number can break arithmetic. Wrap it with
BLANKVALUE(Field__c, 0)or useISBLANKchecks. - Wrong return type. An expression that yields text but is declared as Number fails to save.
- Filtering and reporting. You can filter on a formula in SOQL, but it is not indexed by default. On large objects such filters can be slow.
- Changing a source field. Salesforce blocks edits or deletion of a field that a formula references.
When to use a formula
Use a formula when the value can always be derived from fields on the same record or its parents. If users must override the value, or the calculation needs child records, use another field type.
Exercise
An Opportunity has a Stage picklist. You write the formula IF(StageName = "Closed Won", Amount, 0) and it fails to save. What is wrong, and how do you fix it?
Show answer
Picklist values cannot be compared with a plain equals sign. Use ISPICKVAL(StageName, "Closed Won") instead.