DEV Community

Karim Qalam
Karim Qalam

Posted on Originally published at karimqalam-guides.blogspot.com

Excel IF for SQL people: CASE WHEN in a cell

If you write SQL for a living, the Excel IF function is CASE WHEN. Same idea, worse syntax, no ELSE unless you ask for it.

CASE WHEN amount > 100 THEN 'big' ELSE 'small' END
Enter fullscreen mode Exit fullscreen mode

becomes

=IF(A2>100,"big","small")
Enter fullscreen mode Exit fullscreen mode

Comma instead of THEN, quotes around text, no END. That is the whole translation.

Nested conditions are just ELSE IF chains

CASE
  WHEN amount >= 1000 THEN 'large'
  WHEN amount >= 100 THEN 'medium'
  ELSE 'small'
END
Enter fullscreen mode Exit fullscreen mode
=IF(A2>=1000,"large",IF(A2>=100,"medium","small"))
Enter fullscreen mode Exit fullscreen mode

Read it inside out. Each IF sits in the else position of the one before it. Order matters, exactly like CASE: the first true branch wins, so put the narrowest condition first.

Two things to know that SQL people trip on:

  • Excel has no short circuit guarantee you can rely on in the same way, and a division by zero inside a branch you thought was unreachable still returns an error. Guard the divisor, do not rely on branch order.
  • A missing ELSE in SQL gives NULL. A missing third argument in Excel gives FALSE, printed in the cell. If you see FALSE in a report, someone wrote a two-argument IF.

The NULL problem

SQL NULL is not equal to anything, including itself. Excel has no NULL. An empty cell is 0 in arithmetic and empty string in text comparison, which quietly changes results.

Check emptiness explicitly:

=IF(A2="","missing",A2*2)
Enter fullscreen mode Exit fullscreen mode

That is the equivalent of COALESCE with a guard, and it is the single most common fix I make in shared workbooks.

Multiple conditions without nesting

AND and OR replace the compound WHEN:

=IF(AND(B2="Paid",C2>250),"review","ok")
Enter fullscreen mode Exit fullscreen mode

AND needs every condition true. OR needs one. Both take up to 255 conditions, which is plenty and usually a sign you want a lookup table instead.

When it gets long, stop nesting

Past three levels, a nested IF is unreadable and someone will break it. Two better options:

  1. A lookup table. Two columns, lower bound and label, then VLOOKUP(A2,table,2,TRUE). This is a range join, and it is the closest thing Excel has to a CASE on ranges.
  2. IFS. =IFS(A2>=1000,"large",A2>=100,"medium",TRUE,"small"). The final TRUE,"small" is your ELSE. Excel 2019 and later only.

The test I run before shipping a formula

Put a row with the boundary value in it. 99, 100, 101. If the labels come back wrong at the boundary, the comparison operator is wrong, not the logic. This takes ten seconds and catches most of the bugs I have shipped in spreadsheets.

The full guide with nested examples, error fixes, and a practice workbook is on my blog: Excel IF function.

Top comments (0)