CASE expressions

Turn values into labels

Lesson 6 of 20 · 8 min · Module 2: Ask precise questions

Reports often need human-readable categories rather than raw numbers. CASE chooses a result value based on conditions.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Use conditions inside a result expression
  • Name a calculated column
  • Keep categorization distinct from filtering

The idea

A searched CASE expression reads CASE WHEN condition THEN value ELSE value END. Conditions are checked in order. Use an alias to name the calculated column.

SELECT name,
  CASE WHEN xp >= 200 THEN 'High' ELSE 'Growing' END AS level
FROM learners;

01Label without removing rows

CASE changes a value in the selected result. WHERE removes rows before they reach that result. Use CASE when you want to keep the learners and describe them.

02Provide a fallback

ELSE makes the remaining category explicit. Without it, rows that match no WHEN branch produce NULL for the CASE expression.

Your turn

Return name and a level of 'High' for XP at least 200, otherwise 'Growing'. Name the calculated column level and sort by name.

What the checks look for

  • Labels all five learners and sorts by name
Try it in the editor →

Take this with you

Use CASE to describe records and WHERE to select records.

Learn SQL Foundations for free

20 short lessons with real code and instant checks.

See the whole course →