Sub topic 5
Handling blanks and avoiding divide-by-zero
This chapter assumes you can create a formula field and know the return types (Text, Number, Date, and so on). It covers what a blank value does inside a formula and how to stop a division from failing.
Why blanks cause trouble
A field with no value is blank. Blanks cause two kinds of problems in formulas:
- A text formula that joins or compares a blank field can return an empty or misleading result.
- A division where the divisor is blank or 0 fails. Salesforce shows
#Error!in the field for that record.
The formula editor does not warn you about either problem. It only checks syntax, so the formula saves and then fails on the records that have blanks.
Test for blanks with ISBLANK and BLANKVALUE
ISBLANK(field) returns true when the field has no value. BLANKVALUE(expression, substitute) returns the expression, or the substitute when the expression is blank. BLANKVALUE is the shorter choice when you only need a default value.
IF(BLANKVALUE(Amount, 0) > 100000, "Large",
IF(BLANKVALUE(Amount, 0) > 10000, "Medium", "Small"))An Opportunity with no Amount is treated as 0 and gets the label "Small".
Use ISBLANK when you need a different branch, not a default. Use it instead of ISNULL, which Salesforce recommends against for new formulas.
IF(ISBLANK(Description), "No description", LEFT(Description, 50))The blank-as-zero setting
When you save a formula, Salesforce asks how to treat blank number, currency, and percent fields. The choices are "Treat blank fields as zeroes" and "Treat blank fields as blanks". The first is the default. It makes Amount * 2 return 0 for a blank Amount. The second makes the same formula return blank. Pick the setting deliberately, because it changes what your guards need to catch.
Guard every division
Any division where the divisor can be 0 or blank needs a check first. This formula averages a roll-up total over a roll-up count:
IF(Line_Item_Count__c = 0, 0, Total_Amount__c / Line_Item_Count__c)If the count is 0, the formula returns 0. Otherwise it divides. If the divisor could be blank and you chose "Treat blank fields as blanks", wrap it with BLANKVALUE(Line_Item_Count__c, 0) in the test.
Common mistakes
- Checking
ISBLANKon a number field that is set to 0. Zero is a value, soISBLANKis false. Test= 0as well. - Guarding the numerator but not the divisor.
- Testing a picklist with
ISBLANKand then comparing it directly. UseISPICKVAL(Field, "")for an empty picklist.
Exercise
A formula field on Opportunity is Amount / Quantity__c. It shows #Error! for some records. Rewrite it so those records show 0.
Show answer
IF(BLANKVALUE(Quantity_c, 0) = 0, 0, Amount / Quantityc). The guard handles both a blank and a zero Quantity_c, so the division only runs when the divisor is a nonzero number.