CPCODELAB
SQL

CASE Expressions — Conditional Logic in SQL

9 min read

CASE Expressions

The CASE expression is SQL's version of an if-else statement. It evaluates conditions in order and returns the value from the first WHEN branch that matches. If no branch matches and there is no ELSE, the expression returns NULL.

Searched CASE

sql
-- Classify scores into grade bands
SELECT
  student_id,
  score,
  CASE
    WHEN score >= 90 THEN 'A'
    WHEN score >= 75 THEN 'B'
    WHEN score >= 60 THEN 'C'
    WHEN score IS NOT NULL THEN 'F'
    ELSE 'No score'
  END AS grade
FROM enrolments;

Simple CASE

The *simple* form compares one expression against a list of values — handy when you are mapping discrete values to labels.

sql
-- Map category codes to display names
SELECT
  title,
  CASE category
    WHEN 'DB'   THEN 'Databases'
    WHEN 'WEB'  THEN 'Web Development'
    WHEN 'DATA' THEN 'Data Science'
    ELSE category
  END AS category_label
FROM courses;

CASE can appear anywhere an expression is valid: in SELECT, WHERE, ORDER BY, and even inside aggregate functions. For example, SUM(CASE WHEN score >= 60 THEN 1 ELSE 0 END) counts passing scores.

Use CASE inside GROUP BY to bucket continuous values into discrete groups without creating a separate lookup table. This technique is called *bucket aggregation*.

Ready to test yourself?
Practice SQL— quiz & coding exercises