Sub topic 18
Best practices and troubleshooting
This chapter assumes you can write formula fields with IF, CASE, and BLANKVALUE. It also assumes you have built a roll-up summary field on a master-detail relationship. Here you will collect the habits that prevent problems and a method for diagnosing the ones that still happen.
Design habits that prevent problems
Pick the lightest tool first
Start with a formula when the value can be derived from the record or its parents at read time. Use a roll-up when you need to total, count, or find the minimum or maximum of child records on a master-detail relationship. Move to Flow or Apex only when a requirement falls outside those tools, such as a lookup relationship, a roll-up type other than COUNT, SUM, MIN, or MAX, or a stored value that must be indexed or reported on historically.
Keep formulas readable
Formulas are logic that other admins must maintain. Three habits help:
- Use line breaks and indentation. Whitespace does not change the result.
- Add comments with
/* ... */to explain business rules. - Replace long IF chains with CASE when you compare one field against many exact values.
/* Stage score used by the pipeline dashboard */
CASE(StageName,
"Prospecting", 10,
"Qualification", 25,
"Closed Won", 100,
0)Handle blanks on purpose
Most formula errors that users see come from blank inputs. Decide what a blank should mean and say so in the formula.
- Number and currency fields: wrap with
BLANKVALUE(field, 0)when blank should count as zero. - Division: test the denominator first, as in
IF(Line_Item_Count__c = 0, 0, Total_Amount__c / Line_Item_Count__c). - Text: use
ISBLANK()orISPICKVAL()for picklists instead of comparing to an empty string. - Compare the precision of the checkbox "Treat blank fields as zeroes" option with the behavior you want. Blank handling is a field setting, so check it when results differ from what you expect.
Respect what formulas cannot do
A formula field is calculated when it is read. It is not stored as editable data, so you cannot set it in DML or edit it on a page. Formula fields also cannot trigger automation by themselves, because a change in a formula result is not a save on the record. If you need to react to a derived value, react to the inputs that feed it.
Plan for limits before you hit them
| Area | What to watch | Safer approach |
|---|---|---|
| Formula size | Character and compiled-size limits | Split logic into helper formula fields, then reference them |
| Cross-object formulas | A cap on unique relationships per object | Reuse a single traversal where possible, or copy a parent value into a field with automation |
| Roll-ups | A per-object cap, 25 by default | Retire unused roll-ups, and use Flow or Apex for lookup relationships |
| Roll-up locking | Parent record locked during child saves | Load data in smaller batches, and order records by parent |
| SOQL filters | Formula fields are not indexed by default | Filter on indexed source fields, or ask Salesforce Support about a custom index |
Check the current limits in the Salesforce documentation for your edition, because the numbers can change between releases.
Test with realistic edge cases
Before releasing a calculated field, test records with these inputs:
- All inputs blank.
- Zero values, including a zero denominator.
- Negative values and past dates.
- A parent record that is missing, for cross-object formulas.
- A parent with many children, for roll-ups. Include children that do and do not meet the filter criteria.
A troubleshooting method
Work from the symptom to the cause in a fixed order. This avoids guessing.
Formula errors on save
- Syntax error: Look for a missing comma, an unbalanced parenthesis, or a misspelled field API name. Custom field names end in
__c. - Incorrect return type: The final expression must match the declared type. A Text formula cannot return a number, so wrap numbers in
TEXT(). - Compiled formula is too big: Break the logic into separate formula fields and reference those.
- Function arguments mismatch: IF needs the same data type in both result branches. CASE needs the same type in all results.
Formula returns an unexpected value
- Check whether an input is blank and whether the blank handling setting matches your intent.
- A date formula using
TODAY()changes each day.CloseDate - TODAY()is negative for past dates, which may be correct. - Picklist values need
ISPICKVAL(Field, "Value")orTEXT(Field). Comparing the picklist directly will not compile. - If the formula traverses a relationship, confirm that the parent record exists and that users can see the parent field. Field-level security can hide a result for some users.
Roll-up errors and surprises
- Filter mismatch: The filter is evaluated on the detail records. Compare each child record to the filter criteria and look at checkbox or picklist values.
- Stale value after editing the definition: Changing roll-up criteria does not update existing master records on its own. Use the recalculate option on the field's detail page.
- Wrong summary type: SUM works on number, currency, and percent fields. COUNT does not take a field. MIN and MAX also work on date fields.
- Lock errors: A message such as
UNABLE_TO_LOCK_ROWduring bulk loads means several child saves contended for the same master record. Reduce batch size, sort by master Id, or load in a serial mode.
Reading calculated values in code
Formula and roll-up fields are read-only in DML. After an insert or update, query the record again to see the calculated value. The in-memory record does not contain it.
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);A related trap is a formula that depends on a parent roll-up. In a before trigger on the child, the parent's roll-up has not yet been updated, so the value you read is the old one.
A pre-release checklist
- The return type is correct and the formula compiles.
- Blanks and zero denominators are handled explicitly.
- Each cross-object reference has been tested with and without a parent.
- Roll-up filters match the business definition, and a sample was verified by hand.
- Field-level security was checked for the profiles that will use the field.
- Bulk data loads were tested for lock errors.
- The field has a description that states its business rule.
Exercise
A TotalAmountc roll-up on Invoicec shows 0 for an invoice that has three line items, and the roll-up uses the filter IsBillable__c EQUALS True. What two things would you check first, and how would you fix each?
Show answer
First, check whether the line items have IsBillable_c set to true. The filter is evaluated on the detail records, so non-billable items are excluded and the total is 0. Fix the data or the filter. Second, check whether the roll-up was created or its criteria changed after the records were saved. In that case the stored value is stale, so run the recalculate option on the roll-up field's detail page.
Exercise
A Number formula Total_Amount__c / Line_Item_Count__c fails for invoices with no line items. Rewrite it so it returns 0 instead of an error.
Show answer
Use IF(LineItemCount_c = 0, 0, TotalAmount_c / LineItemCount_c). The test on the denominator prevents the division when the count is zero.