SQL 102· Level 1

CASE WHEN

CASE builds a new column by putting each row into a category you describe. It reads like a list of if-then rules:

CASE WHEN mark >= 50 THEN 'Pass' ELSE 'Fail' END

  • Each WHEN is a test, and THEN is the value to use if the row passes it.
  • The tests are tried from the top and the first one that passes wins. The rest are skipped.
  • ELSE catches every row left over. Without an ELSE, those rows get NULL.
  • It always finishes with END, usually followed by AS and a column name.

A CASE can go anywhere a column can, including inside an aggregate. SUM(CASE WHEN grade = 'F' THEN 1 ELSE 0 END) counts the fails. AI-written queries use this pattern often to count several things side by side.

Worked example

Label each 2026 enrolment in ARTS202 as Pass, Fail or In progress.

SELECT student_id, session, mark,
  CASE
    WHEN mark >= 50 THEN 'Pass'
    WHEN mark < 50 THEN 'Fail'
    ELSE 'In progress'
  END AS result
FROM enrolments
WHERE unit_code = 'ARTS202'
  AND year = 2026
ORDER BY session, student_id
Getting the practice database ready…

This takes a few seconds the first time. Nothing leaves your computer.

Exercises in this level