Skip to content
Bronze 6 min read · Expressions 3 practice problems ↓

CASE WHEN and expressions

Reports are full of labels that are not in the data: small, medium and large orders; on time or late; weekday or weekend. CASE turns values into such labels, row by row. This lesson shows how it works, the order it checks its conditions in, and the NULL trap in its short form.

Foundations · SQL for data engineers · Bronze · Reading a table, lesson 3 of 3

Read first: SELECT, WHERE and ORDER BY · NULL and three-valued logic (skip if you know them)

In plain words first

Think of a teacher turning marks into grades: 90 or more is an A, 75 or more is a B, everything else is a C. They read the rules from the top and stop at the first one that fits: 92 is an A, and they never even look at the B rule.

CASE is that list of rules, applied to every row. The rules are checked from the top, the first match wins, and a row that fits no rule gets the ELSE value, or NULLNULL: A missing or unknown value. It is not 0 or an empty string, and any comparison with it is unknown instead of true or false. Learn more → if there is no ELSE.

CASE: if, then, else for every row

CASE is SQL's if-else. It is an expression, so it works anywhere a value does: in SELECT, WHERE, ORDER BY or inside an aggregateaggregate: A function that turns many rows into one value: count, sum, avg, min, max. With GROUP BY it gives one value per group. Learn more →. The usual form tests a condition in each branch:

Syntax

CASE
  WHEN condition_1 THEN value_1
  WHEN condition_2 THEN value_2
  ELSE fallback
END

SQL checks the WHEN branches from top to bottom and returns the value of the first one whose condition is true. Without an ELSE, a row that matches no branch gets NULL.

Bucketing numbers into labels

Spark SQL · Order sizes

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT order_id,
       amount,
       CASE
         WHEN amount IS NULL THEN 'unknown'
         WHEN amount >= 500 THEN 'large'
         WHEN amount >= 300 THEN 'medium'
         ELSE 'small'
       END AS size
FROM orders

Each branch only needs a lower bound, because the branches above it already took the larger amounts: an order of 540 stops at large and never reaches medium. Swap the two middle branches and every order from 300 up becomes medium, since 540 >= 300 is checked first. Put the most specific test first.

The NULL branch comes first on purpose. Without it, order 103 would fall through every comparison (each is NULL, not true) and land in ELSE as small, which is wrong: we do not know its size.

Simple CASE, and why it never matches NULL

When every branch compares the same column with =, there is a shorter form: CASE status WHEN 'delivered' THEN ... END. It is easy to read, but it compares with =, so a WHEN NULL branch can never match:

Spark SQL · WHEN NULL is never chosen

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT order_id,
       status,
       CASE status
         WHEN 'delivered' THEN 'done'
         WHEN NULL THEN 'missing'
         ELSE 'other'
       END AS label
FROM orders

Order 104 gets other, not missing: the test is status = NULL, which is NULL. Use the searched form, WHEN status IS NULL THEN 'missing', whenever NULL needs its own label.

CASE in ORDER BY: a custom order

Statuses sort alphabetically by default, which is rarely the order people want to read them in. Map each one to a number and sort by that:

Spark SQL · Problems first, then the rest

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT order_id, status
FROM orders
ORDER BY CASE
           WHEN status IS NULL THEN 1
           WHEN status = 'cancelled' THEN 2
           WHEN status = 'refunded' THEN 3
           ELSE 4
         END,
         order_id

Shortcuts: IF, COALESCE and arithmetic

Instead ofWriteNotes
CASE WHEN c THEN a ELSE b ENDif(c, a, b)Spark and BigQuery. Fine for one condition; CASE reads better for several.
CASE WHEN x IS NULL THEN y ELSE x ENDcoalesce(x, y)Works everywhere, and takes more than two arguments.
CASE WHEN q = 0 THEN NULL ELSE p / q ENDp / nullif(q, 0)No division by zero, in every database.

One more thing about arithmetic: in Spark, / always returns a decimal number, so 7 / 2 is 3.5. PostgreSQL and SQL Server divide integers to an integer (3). Use 7 div 2 in Spark when you want the whole part, and round(x, 2) to round.

Spark SQL · Shortcuts at work

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT order_id,
       if(status = 'delivered', 'yes', 'no') AS delivered,
       coalesce(amount, 0) AS amount,
       round(coalesce(amount, 0) / 3, 2) AS split_three_ways
FROM orders

Look at order 104 in the delivered column: its status is NULL, so the condition is NULL, and IF (like CASE) takes the else branch. "Not known to be delivered" became "no". Often that is what you want; be sure it is.

Common mistakes

  • Putting the broad branch first — With WHEN amount >= 300 above WHEN amount >= 500, the second branch can never be reached. Order branches from most to least specific.
  • Testing for NULL in a simple CASE — CASE col WHEN NULL compares with = and never matches. Use CASE WHEN col IS NULL.
  • Forgetting ELSE — Unmatched rows silently become NULL, and later filters or counts drop them. Write an ELSE, even if it is ELSE 'other'.
  • Mixing types in the branches — THEN 1 ... ELSE 'n/a' forces one type for the whole column. Keep every branch the same type, or cast on purpose.

Key takeaways

  • CASE returns the value of the first WHEN that is true, and NULL when none is and there is no ELSE.
  • Order branches from most to least specific, and test IS NULL before any comparison.
  • A simple CASE compares with =, so WHEN NULL never matches.
  • CASE works in SELECT, WHERE, ORDER BY and inside aggregates, which is the next lesson's trick.

Interview prep

THE QUESTION

"Label every order small, medium or large by amount. Some amounts are missing. Walk me through your CASE."

Branches go most specific first, and NULL is handled before any comparison: WHEN amount IS NULL THEN 'unknown' WHEN amount >= 500 THEN 'large' WHEN amount >= 300 THEN 'medium' ELSE 'small'. The first true branch wins, so each needs only a lower bound. Without the NULL branch a missing amount falls through to ELSE and is labelled small, which would make the small bucket look bigger than it is.

Avoid: "I would write CASE WHEN amount < 300 THEN 'small' WHEN amount < 500 THEN 'medium' ELSE 'large' END." It reads well, but a missing amount fails both tests and is labelled large.

Follow-ups · answer out loud, then open

Follow-up"Can you use CASE inside an aggregate? Show me."
Yes, and it is one of the most useful patterns in SQL: sum(CASE WHEN status = 'delivered' THEN amount ELSE 0 END) totals only delivered orders, inside an ordinary GROUP BY. One query can compute many such columns at once.
Scenario"Product wants statuses shown in a fixed order: pending, shipped, delivered, returned, never alphabetically. How?"
ORDER BY a CASE that maps each status to a number: ORDER BY CASE status WHEN 'pending' THEN 1 WHEN 'shipped' THEN 2 WHEN 'delivered' THEN 3 ELSE 4 END. If the order is used in many places, keep it in a small lookup table with a sort column and join to it.
Trap"CASE WHEN x > 0 THEN 'pos' WHEN x < 0 THEN 'neg' END. What do zero and NULL return?"
Both return NULL: there is no ELSE, and neither comparison is true for 0 or for NULL. If the column must always have a label, add WHEN x = 0 THEN 'zero', WHEN x IS NULL THEN 'unknown' or an ELSE.

Check yourself

4 questions

An amount is 540. Branches are WHEN amount >= 300 THEN 'medium' WHEN amount >= 500 THEN 'large'. What is the label?

Show the answer

medium. The first true branch wins, and 540 >= 300 is checked first.

A row matches no WHEN and there is no ELSE. What does CASE return?

Show the answer

NULL. A CASE without ELSE returns NULL for unmatched rows.

What does CASE status WHEN NULL THEN 'x' ELSE 'y' END return when status is NULL?

Show the answer

'y'. A simple CASE tests status = NULL, which is never true.

What is 7 / 2 in Spark SQL?

Show the answer

3.5. In Spark, / always returns a decimal result; div gives the integer part.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · new module: Summarising · 6 min read
GROUP BY and HAVING
Collapse rows into one per group, filter groups with HAVING, and the rule for what SELECT may show.

Related lessons

Previous: NULL and three-valued logic

Primary sources: CASE clause · Built-in functions (if, coalesce, nullif)