SQL reference

SQL CASE WHEN: IF logic in a query

In Excel, you'd reach for
fx=IF(), nested IFs or =IFS()

CASE WHEN turns rules into a new column. SQL checks each WHEN from top to bottom and uses the first one that's true; ELSE catches the rest. Leave ELSE out and unmatched rows get an empty value.

Business uses: bucket deals by size, flag late tickets, group countries into regions, label plans as free or paid.

Syntax

CASE
  WHEN condition_1 THEN result_1
  WHEN condition_2 THEN result_2
  ELSE fallback
END
Try itEdit the query, then Run
idpriorityspeed
1normalwithin a day
2lowtook longer
3lowtook longer
4lowtook longer
5lowtook longer
6normaltook longer
7normalwithin a day
8normalwithin a day
9lowwithin a day
10normalwithin a day

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

CASE inside a total

Put CASE inside SUM or COUNT to get several conditional totals in one row, the SQL version of COUNTIFS side by side:

SELECT
  SUM(CASE WHEN priority = 'urgent' THEN 1 ELSE 0 END) AS urgent,
  SUM(CASE WHEN priority = 'low' THEN 1 ELSE 0 END) AS low
FROM tickets;

CASE works the same in every major database. Some also have a shorter IF() or IIF() for a single condition.

Your turn

Label each order 'big' when quantity is 4 or more, otherwise 'small', as size, and count orders per size as orders.

This page on one card

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

See every column and sample rows