Ira SQL ProIra SQL Pro

SQL CASE WHEN Expression

intermediateadvanced
2 min read

What is CASE WHEN?

CASE WHEN is SQL's conditional expression, similar to if/else in programming. It evaluates conditions and returns a value for the first true condition.

Syntax

Searched CASE:

CASE
  WHEN condition1 THEN result1
  WHEN condition2 THEN result2
  ELSE default_result
END

Simple CASE:

CASE column
  WHEN value1 THEN result1
  WHEN value2 THEN result2
  ELSE default_result
END

When to Use

  • Categorizing data into buckets (age groups, price tiers)
  • Conditional aggregation
  • Custom sort orders
  • Transforming codes into readable labels

Key Points

  1. First Match Wins — Conditions are evaluated in order.
  2. ELSE is Optional — If no condition matches and there is no ELSE, the result is NULL.
  3. Anywhere — CASE can be used in SELECT, WHERE, ORDER BY, GROUP BY, and inside aggregate functions.
  4. Conditional AggregationSUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) counts active rows.
  5. Nesting — You can nest CASE expressions, but consider readability.

Guided Practice

Solve the challenge below. Use hints when stuck and check your answer for instant feedback.

Practice challengeGuided learning mode

SQL CASE WHEN Expression Challenge

Write a query that solve this task: label students as Junior, Senior, or Graduate.

Expected result

Each student with an age-based category label.

Hidden checks

  • Returned rows and values
  • Output columns and result shape
  • Final database state after the query runs

Lesson guidance

What is CASE WHEN?

Initializing database...Each run starts from fresh sample data.

More Examples

Conditional aggregation

Count students in each grade category.

Initializing database...Each run starts from fresh sample data.

Frequently Asked Questions

What happens if no condition matches in CASE WHEN?
If no condition is true and there is no ELSE clause, the expression returns NULL.
Can I use CASE WHEN in ORDER BY?
Yes. For example: ORDER BY CASE WHEN priority = 'high' THEN 1 ELSE 2 END; to create a custom sort.

Related Topics