CASE Expressions

Updated · 9 min read
mediumPostgreSQL 18sqlcaseconditionalpivotfilterinterview

CASE is SQL's if-then-else: it checks conditions in order and returns the value for the first one that's true. A payment is "On time" if it was paid by its due date and "Late" otherwise; a course is "Premium", "Standard" or "Starter" by its fee. Neither label is stored anywhere; CASE works it out in the query. This lesson covers both forms of CASE, using it in SELECT and ORDER BY, and its most useful trick: counting and totaling only the rows that match a condition, inside an aggregate.

In One Minute

  • CASE WHEN condition THEN value ... ELSE value END returns the value of the first true condition.
  • Without ELSE, an unmatched row gets NULL.
  • The simple form CASE column WHEN value THEN ... compares one column with values, but can't match NULL.
  • Inside an aggregate, CASE counts or sums only some rows: sum(CASE WHEN ... THEN amount_usd ELSE 0 END).
  • PostgreSQL also has count(*) FILTER (WHERE ...); SQL Server has IIF, MySQL has IF.

The Searched CASE

SQL
CASE
  WHEN condition_1 THEN result_1
  WHEN condition_2 THEN result_2
  ELSE default_result
END

Was each payment on time?

SQL▶ Try it
SELECT payment_id, due_on, paid_on,
       CASE WHEN paid_on <= due_on THEN 'On time'
            ELSE 'Late'
       END AS timing
FROM payments
ORDER BY payment_id;
Output
 payment_id |   due_on   |  paid_on   | timing
------------+------------+------------+---------
          1 | 2025-09-01 | 2025-08-28 | On time
          2 | 2025-11-01 | 2025-10-30 | On time
          3 | 2025-12-01 | 2025-12-03 | Late
          4 | 2026-01-02 | 2025-12-29 | On time
          5 | 2026-01-05 | 2026-01-05 | On time
          6 | 2025-11-15 | 2025-11-14 | On time
          7 | 2025-12-15 | 2025-12-19 | Late
(7 rows)

Payments 3 and 7 were paid after their due dates. CASE ... END is an expression, like amount_usd * 2: it produces one value per row, and AS timing names the column.

Conditions are checked from top to bottom, and the first true one wins. That makes ranges easy, because each WHEN only needs its lower bound:

SQL▶ Try it
SELECT title, fee_usd,
       CASE WHEN fee_usd >= 500 THEN 'Premium'
            WHEN fee_usd >= 400 THEN 'Standard'
            ELSE 'Starter'
       END AS tier
FROM courses
ORDER BY fee_usd DESC;
Output
       title       | fee_usd |   tier
-------------------+---------+----------
 Java Collections  |  550.00 | Premium
 Java OOP          |  500.00 | Premium
 Java Basics       |  450.00 | Standard
 JavaScript Basics |  450.00 | Standard
 SQL Basics        |  400.00 | Standard
 Git Basics        |  250.00 | Starter
(6 rows)

Java OOP's $500.00 also satisfies fee_usd >= 400, but the first WHEN already matched, so it's Premium. Swap the two WHENs and every course from $400 up becomes Standard.

Each fee falls through the WHEN lines from the top; the first true one gives its tier

The Simple CASE

When every condition compares the same column with a value, the simple form is shorter:

SQL▶ Try it
SELECT payment_id,
       CASE method
         WHEN 'card'  THEN 'Card'
         WHEN 'check' THEN 'Check'
         ELSE 'Unknown'
       END AS method_label
FROM payments
ORDER BY payment_id;
Output
 payment_id | method_label
------------+--------------
          1 | Card
          2 | Card
          3 | Check
          4 | Card
          5 | Unknown
          6 | Card
          7 | Check
(7 rows)

Payment 5, with no method, fell through to ELSE. Careful: the simple form compares with =, so CASE method WHEN NULL THEN ... never matches, because NULL = NULL is unknown. To test for NULL, use the searched form: CASE WHEN method IS NULL THEN 'missing' ....

All the results must have compatible types. CASE WHEN ... THEN 1 ELSE 'x' END fails, because PostgreSQL decides the column is a number and 'x' isn't one.

CASE in ORDER BY

CASE can define a custom sort order, for values whose alphabetical order isn't the order you want:

SQL▶ Try it
SELECT title, level
FROM courses
ORDER BY CASE level WHEN 'Beginner' THEN 1 WHEN 'Intermediate' THEN 2 END,
         title;
Output
       title       |    level
-------------------+--------------
 Git Basics        | Beginner
 Java Basics       | Beginner
 JavaScript Basics | Beginner
 SQL Basics        | Beginner
 Java Collections  | Intermediate
 Java OOP          | Intermediate
(6 rows)

Beginner courses first, then Intermediate, each group sorted by title. Here alphabetical order happens to agree, but add an 'Advanced' level and you'd need the CASE to put it last.

Conditional Counting and Totals

Put CASE inside an aggregate to count or total only the rows that match. How many payments were late, and how many by card?

SQL▶ Try it
SELECT count(*) AS payments,
       sum(CASE WHEN paid_on > due_on THEN 1 ELSE 0 END) AS late,
       count(CASE WHEN method = 'card' THEN 1 END) AS by_card
FROM payments;
Output
 payments | late | by_card
----------+------+---------
        7 |    2 |       4
(1 row)

sum(CASE ... THEN 1 ELSE 0 END) adds 1 for each matching row. count(CASE ... THEN 1 END) works too: non-matching rows get NULL, and count skips NULL. PostgreSQL has a clearer way to say the same thing, count(*) FILTER (WHERE paid_on > due_on) (standard SQL, supported by PostgreSQL and SQLite, but not MySQL or SQL Server).

The same idea spreads one column into several, called a pivot. Card and check totals per student, side by side:

SQL▶ Try it
SELECT student_id,
       sum(CASE WHEN method = 'card'  THEN amount_usd ELSE 0 END) AS card_total,
       sum(CASE WHEN method = 'check' THEN amount_usd ELSE 0 END) AS check_total
FROM payments
GROUP BY student_id
ORDER BY student_id;
Output
 student_id | card_total | check_total
------------+------------+-------------
        101 |    1250.00 |      250.00
        103 |     225.00 |      225.00
(2 rows)
Each payment adds its amount to the card or check column for its student

CASE in Other Databases

CASE is standard SQL and works everywhere. Some databases add shorthand for a single if-then-else:

DatabaseShorthandSame as
SQL ServerIIF(paid_on <= due_on, 'On time', 'Late')CASE WHEN ... THEN ... ELSE ... END
MySQLIF(paid_on <= due_on, 'On time', 'Late')CASE WHEN ... THEN ... ELSE ... END
AccessIIf(...) and Switch(...)CASE
PostgreSQLnone; use CASE

Tabs showing each database's version are coming to this course.

One on-time check written as PostgreSQL CASE, SQL Server IIF and MySQL IF

Common Mistakes

Conditions in the wrong order. The first true WHEN wins; put the most specific first.

Forgetting ELSE. Unmatched rows become NULL.

CASE column WHEN NULL. It never matches. Use CASE WHEN column IS NULL.

Mixed result types. All results must be compatible; convert with ::text if needed.

Interview Corner

What does a CASE expression do?

It evaluates conditions in order and returns the result of the first true one, or the ELSE value, or NULL if there's no ELSE. It's SQL's if-then-else.

How do you count rows matching a condition alongside a total count?

count(*) for the total and sum(CASE WHEN condition THEN 1 ELSE 0 END), or count(*) FILTER (WHERE condition) in PostgreSQL, in the same SELECT.

What's the difference between simple and searched CASE?

The simple form compares one expression with a list of values using =; the searched form evaluates arbitrary conditions, and is the only one that can test for NULL.

Practice

Challenge: For each payment, show payment_id, the amount, and a size label: 'Large' for $500 or more, 'Medium' for $250 up to $499.99, and 'Small' for anything less. Sort by payment_id.

Show solution
SQL▶ Try it
SELECT payment_id, amount_usd,
       CASE WHEN amount_usd >= 500 THEN 'Large'
            WHEN amount_usd >= 250 THEN 'Medium'
            ELSE 'Small'
       END AS size
FROM payments
ORDER BY payment_id;
Output
 payment_id | amount_usd |  size
------------+------------+--------
          1 |     450.00 | Medium
          2 |     250.00 | Medium
          3 |     250.00 | Medium
          4 |     550.00 | Large
          5 |     200.00 | Small
          6 |     225.00 | Small
          7 |     225.00 | Small
(7 rows)

Payment 4 ($550.00) is Large. Payments 1, 2 and 3 are Medium; the two $250.00 installments count because >= 250 includes 250. The rest are Small.

Quick check: CASE expressions

3 questions
1CASE WHEN fee_usd >= 400 THEN 'Standard' WHEN fee_usd >= 500 THEN 'Premium' END: what does a $550 course get?
2A CASE has no ELSE, and no WHEN matches. What's returned?
3Which counts late payments?

Key Takeaways

You want toWrite
Label rowsCASE WHEN paid_on <= due_on THEN 'On time' ELSE 'Late' END
Translate codesCASE method WHEN 'card' THEN 'Card' ELSE 'Unknown' END
Count matchessum(CASE WHEN paid_on > due_on THEN 1 ELSE 0 END)
PostgreSQL shortcutcount(*) FILTER (WHERE paid_on > due_on)

Was this tutorial helpful?

Lesson 49 of 115