Tsallaka zuwa abun ciki
Justice Tech School

CASE

CASE goes through conditions in order and returns the value of the first one that is true, like if / else if. Always add an ELSE to cover everything else.

Example
SELECT name, score,
  CASE
    WHEN score >= 85 THEN 'Distinction'
    WHEN score >= 70 THEN 'Pass'
    ELSE 'Retake'
  END AS grade
FROM students
WHERE score IS NOT NULL
ORDER BY score DESC
LIMIT 4;

Result

name   | score | grade
Ada    | 92    | Distinction
Zainab | 88    | Distinction
Amina  | 85    | Distinction
Kofi   | 78    | Pass

Exercise

Finish the CASE expression.

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

Quiz Test

What does CASE return when no condition matches and there is no ELSE?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.