Filtering and Sorting · Lesson 16 of 64

SQL CASE

What you will learn

  • How CASE WHEN ... THEN ... ELSE ... END gives each row a value
  • The searched and the simple form
  • How to build labels and groups from numbers
  • How to use CASE in ORDER BY and with NULL

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.

1. CASE gives each row a value

CASE is SQL's "if ... then ... else". The database checks the WHEN conditions in order and returns the THEN value of the first one that is true; if none is true, it returns the ELSE value (or NULL if there is no ELSE). It ends with END:

SELECT name, price,
       CASE WHEN price < 10 THEN 'cheap'
            WHEN price < 40 THEN 'medium'
            ELSE 'expensive' END AS price_class
FROM products ORDER BY product_id LIMIT 8;
name              price  price_class
----------------  -----  -----------
Steel pan           6.6  cheap
Ceramic mug        44.1  expensive
Wooden spoon set   29.5  medium
Glass jar           5.4  cheap
Chopping board     26.4  medium
Tea kettle         79.0  expensive
Lunch box          29.5  medium
Hand trowel        20.9  medium
(8 rows)
SELECT account_id, balance_cents,
       CASE WHEN balance_cents < 50000 THEN 'small'
            WHEN balance_cents < 200000 THEN 'medium'
            ELSE 'large' END AS size
FROM accounts ORDER BY account_id LIMIT 8;
account_id  balance_cents  size
----------  -------------  ------
         1         192400  medium
         2          52078  medium
         3          62780  medium
         4          99900  medium
         5         153100  medium
         6         218400  large
         7           9886  small
         8         122464  medium
(8 rows)
SELECT code, title, credits,
       CASE WHEN credits >= 4 THEN 'heavy'
            WHEN credits = 3 THEN 'standard'
            ELSE 'light' END AS load
FROM courses ORDER BY course_id LIMIT 8;
code     title                   credits  load
-------  ----------------------  -------  --------
MATH101  Foundations of Algebra        4  heavy
MATH201  Geometry                      3  standard
MATH301  Statistics                    4  heavy
SCI101   General Science               4  heavy
SCI201   Chemistry                     4  heavy
SCI202   Physics                       4  heavy
SCI301   Biology                       3  standard
LANG101  Writing Skills                3  standard
(8 rows)

The order of the WHENs matters: the first true one wins. Put the narrowest condition first. Here price < 10 comes before price < 40, so a price of 5 is cheap, not medium.

2. The simple form

When every WHEN compares the same value for equality, the simple form is shorter:

SELECT status,
       CASE status WHEN 'pending' THEN 'waiting' WHEN 'paid' THEN 'in progress' WHEN 'shipped' THEN 'on its way'
                   WHEN 'delivered' THEN 'done' ELSE 'stopped' END AS meaning
FROM orders GROUP BY status ORDER BY status;
status     meaning
---------  -----------
cancelled  stopped
delivered  done
paid       in progress
pending    waiting
shipped    on its way
(5 rows)
SELECT kind,
       CASE kind WHEN 'deposit' THEN 'money in' WHEN 'interest' THEN 'money in' WHEN 'transfer_in' THEN 'money in'
                 ELSE 'money out' END AS direction
FROM transactions GROUP BY kind ORDER BY kind;
kind          direction
------------  ---------
deposit       money in
fee           money out
interest      money in
transfer_in   money in
transfer_out  money out
withdrawal    money out
(6 rows)
SELECT term,
       CASE term WHEN '2025-Spring' THEN 'first' WHEN '2025-Autumn' THEN 'second' ELSE 'latest' END AS order_in_time
FROM sections GROUP BY term ORDER BY term;
term         order_in_time
-----------  -------------
2025-Autumn  second
2025-Spring  first
2026-Spring  latest
(3 rows)

CASE x WHEN a THEN ... is the same as CASE WHEN x = a THEN .... Use the searched form (section 1) for anything other than equality.

3. Counting groups with CASE

A common use is to count several groups in one query, one column each. CASE gives 1 when the row belongs to the group and 0 otherwise; SUM adds them up (chapter 3 explains SUM):

SELECT SUM(CASE WHEN price < 10 THEN 1 ELSE 0 END) AS cheap,
       SUM(CASE WHEN price >= 10 AND price < 40 THEN 1 ELSE 0 END) AS medium,
       SUM(CASE WHEN price >= 40 THEN 1 ELSE 0 END) AS expensive
FROM products;
cheap  medium  expensive
-----  ------  ---------
    9      28          8
(1 row)
SELECT SUM(CASE WHEN balance_cents < 50000 THEN 1 ELSE 0 END) AS small,
       SUM(CASE WHEN balance_cents >= 50000 AND balance_cents < 200000 THEN 1 ELSE 0 END) AS medium,
       SUM(CASE WHEN balance_cents >= 200000 THEN 1 ELSE 0 END) AS large
FROM accounts;
small  medium  large
-----  ------  -----
   81     268    101
(1 row)
SELECT SUM(CASE WHEN credits >= 4 THEN 1 ELSE 0 END) AS heavy,
       SUM(CASE WHEN credits = 3 THEN 1 ELSE 0 END) AS standard,
       SUM(CASE WHEN credits < 3 THEN 1 ELSE 0 END) AS light
FROM courses;
heavy  standard  light
-----  --------  -----
    7         7      5
(1 row)

4. CASE and NULL

A WHEN condition that is unknown (because of NULL) counts as not true, so the row falls through to the next WHEN or to ELSE. Test for NULL explicitly with IS NULL:

SELECT customer_id, phone,
       CASE WHEN phone IS NULL THEN 'no phone' ELSE 'has phone' END AS phone_status
FROM customers ORDER BY customer_id LIMIT 4;
customer_id  phone         phone_status
-----------  ------------  ------------
          1  +35 49854883  has phone
          2  NULL          no phone
          3  +58 13864688  has phone
          4  +48 26805141  has phone
(4 rows)
SELECT log_id, note,
       CASE WHEN note IS NULL THEN 'no note' ELSE 'has note' END AS note_status
FROM audit_log ORDER BY log_id LIMIT 4;
log_id  note            note_status
------  --------------  -----------
     1  NULL            no note
     2  NULL            no note
     3  limit raised    has note
     4  status changed  has note
(4 rows)
SELECT student_id, guardian_name,
       CASE WHEN guardian_name IS NULL THEN 'no guardian' ELSE 'has guardian' END AS guardian_status
FROM students ORDER BY student_id LIMIT 12;
student_id  guardian_name  guardian_status
----------  -------------  ---------------
         1  Amir Khan      has guardian
         2  Nadia Haque    has guardian
         3  Mina Garcia    has guardian
         4  Femi Meyer     has guardian
         5  Ana Torres     has guardian
         6  Sam Patel      has guardian
         7  NULL           no guardian
         8  Gita Abdi      has guardian
         9  NULL           no guardian
        10  Gita Torres    has guardian
        11  Priya Rahman   has guardian
        12  Sam Sato       has guardian
(12 rows)

5. CASE in ORDER BY

CASE can build a custom sort order, for example to put some values first:

Orders with the status pending first, then the rest:

SELECT order_id, status, order_date FROM orders
ORDER BY CASE WHEN status = 'pending' THEN 0 ELSE 1 END, order_date, order_id LIMIT 6;
order_id  status   order_date
--------  -------  ----------
    2021  pending  2024-01-01
    1689  pending  2024-01-21
    2322  pending  2024-02-29
    2275  pending  2024-03-15
    1707  pending  2024-03-21
     133  pending  2024-05-22
(6 rows)

Frozen accounts first, then the rest:

SELECT account_id, status FROM accounts
ORDER BY CASE WHEN status = 'frozen' THEN 0 ELSE 1 END, account_id LIMIT 6;
account_id  status
----------  ------
        17  frozen
        18  frozen
        88  frozen
        98  frozen
       108  frozen
       153  frozen
(6 rows)

Students enrolled in 2026 first, then the rest:

SELECT student_id, enrolled_year FROM students
ORDER BY CASE WHEN enrolled_year = 2026 THEN 0 ELSE 1 END, student_id LIMIT 6;
student_id  enrolled_year
----------  -------------
         1           2026
         6           2026
         9           2026
        12           2026
        13           2026
        16           2026
(6 rows)

Worked example: turn a number into a label

A report should say low, normal or high instead of a number.

Step Do
1 decide the ranges (for example below 10, 10 to 39, 40 and above)
2 write the narrowest WHEN first: WHEN x < 10 THEN 'low'
3 add the next: WHEN x < 40 THEN 'normal'
4 finish with ELSE 'high' and END
5 give the column a name with AS

Because the first true WHEN wins, x < 40 only applies to values that were not below 10. The ranges are examples.

Common mistakes

  • Forgetting END.
  • Wrong order of WHENs, so a broad condition catches rows meant for a narrower one.
  • No ELSE, which gives NULL for rows that match nothing.
  • Testing NULL with =. Use IS NULL inside the WHEN.
  • Mixing result types (a number in one THEN and text in another) without meaning to.

Key takeaways

  • CASE WHEN cond THEN value ... ELSE value END gives each row a value; the first true WHEN wins.
  • The simple form CASE x WHEN a THEN ... compares one value for equality.
  • SUM(CASE WHEN ... THEN 1 ELSE 0 END) counts several groups in one query.
  • CASE works in SELECT, ORDER BY and elsewhere; test NULL with IS NULL.

Practice

1. Write a CASE that labels a score of 50 or more pass and anything else fail.

Show answer

CASE WHEN score >= 50 THEN 'pass' ELSE 'fail' END

2. What does a CASE return when no WHEN is true and there is no ELSE?

Show answer

NULL.

3. Why does the order of the WHENs matter?

Show answer

The first true WHEN wins, so a broad condition placed first can catch rows meant for a narrower one.

4. Rewrite CASE WHEN status = 'open' THEN 1 WHEN status = 'closed' THEN 2 END in the simple form.

Show answer

CASE status WHEN 'open' THEN 1 WHEN 'closed' THEN 2 END

5. What does SUM(CASE WHEN price > 20 THEN 1 ELSE 0 END) count?

Show answer

The number of rows with a price above 20: each such row adds 1, the others add 0.

6. How do you test for a missing value inside a CASE?

Show answer

With WHEN column IS NULL THEN .... A test with = would never be true.