Sub topic 4
Branching with IF and CASE
This chapter assumes you can create a formula field in Setup, know the return types (Text, Number, Date, Checkbox), and have seen basic operators. It covers the two main branching functions and how to choose between them.
IF: test a condition
IF(condition, value_if_true, value_if_false) evaluates one condition. Both result values must match the formula's return type. To test more than two outcomes, nest IF calls in the false position.
The next formula is a Text formula on Opportunity. It buckets Amount into size labels. BLANKVALUE treats an empty Amount as 0, so the comparison never runs against null.
IF(BLANKVALUE(Amount, 0) > 100000, "Large",
IF(BLANKVALUE(Amount, 0) > 10000, "Medium", "Small"))Salesforce checks the conditions from the outside in and stops at the first true one. Put the most restrictive test first. If you tested > 10000 first, every large deal would be labeled "Medium".
Combine conditions with AND and OR, for example AND(Amount > 10000, IsClosed = false). You can also use && and ||.
CASE: match one value against a list
CASE(expression, value1, result1, value2, result2, ..., else_result) compares one expression with exact values. It fits best when you switch on a single field, such as a stage name.
This Number formula maps a stage to a score. The final 0 is the default for any other stage.
CASE(StageName,
"Prospecting", 10,
"Qualification", 25,
"Closed Won", 100,
0)CASE has these rules:
- It tests equality only. It cannot test
>or<. - The else value is required.
- All results must share one data type.
- The expression must be text, a number, or a date. For a picklist field, wrap the field in
TEXT(). Picklist fields don't work directly inCASE.
Choosing between them
| Situation | Use |
|---|---|
| Compare one field to several exact values | `CASE` |
| Ranges, such as `Amount > 10000` | `IF` |
| Combine several fields in one test | `IF` with `AND` / `OR` |
| Many branches on one field | `CASE`, which is shorter and easier to read |
Common errors
- Type mismatch.
IF(Amount > 0, "Yes", 0)fails because one branch is Text and the other is Number. - Picklist in a text function. Use
ISPICKVAL(StageName, "Closed Won")insideIF. UseTEXT(StageName)insideCASE. - Wrong test order. Overlapping ranges return the first match, not the best match.
- Null in a comparison. Wrap numeric fields in
BLANKVALUEwhen an empty value should count as 0.
Exercise
A Number formula on Opportunity must return 1 for "Prospecting", 2 for "Qualification", and 0 for any other stage. Write it, and say why IF(StageName = "Prospecting", 1, 0) would be a poor starting point.
Show answer
Use CASE(StageName, "Prospecting", 1, "Qualification", 2, 0). StageName is a picklist, so the comparison StageName = "Prospecting" is invalid. A picklist must be wrapped in TEXT() or tested with ISPICKVAL(). For several exact values, CASE is also shorter than nested IF calls.