Excel to SQL · Lesson 9 of 12

IF is CASE WHEN

In Excel, you'd reach for
fx=IF(D2>=5, "Bulk", "Single"), nested IFs, IFS

CASE WHEN is IF, written as a list instead of a nest. SQL checks each WHEN in order and uses the first one that's true. ELSE catches everything left over.

Try itEdit the query, then Run
idquantityorder_size
11single
23few
31single
42few
54few
62few
71single
82few
92few
102few

Showing 10 of 15 rows. Press Run to see them all.

The real power is grouping by the label you just made, which in Excel needs a helper column and then a pivot:

SELECT CASE WHEN quantity >= 5 THEN 'bulk' ELSE 'small' END AS size,
       COUNT(*) AS orders
FROM orders
GROUP BY size;

Your turn

Label each subscription 'paying a lot' when mrr is 100 or more, otherwise 'standard', as a column called tier. Count subscriptions per tier as subs.

This page on one card

IF is CASE WHEN: the Excel way (=IF(D2>=5) and the SQL query, side by side
IF is CASE WHEN, on one card: the Excel way and the SQL. Download · Save to Pinterest
The practice data (7 tables)

See every column and sample rows