0PricingLogin
SQL Academy · Lesson

The CASE Expression

IF/THEN logic inside a query.

Branching Logic in SQL

Sometimes you need a query to make a decision: if this, then that, otherwise something else. SQL gives you the CASE expression for exactly this.

CASE lets you return different values based on conditions, right inside a SELECT. Think of it as SQL's version of an if/else chain.

SELECT name,
       CASE WHEN price > 100 THEN 'expensive'
            ELSE 'affordable'
       END AS price_band
FROM products;

Anatomy of a CASE

A CASE expression has a few parts:

  • WHEN condition THEN value — one or more branches
  • ELSE value — an optional fallback
  • END — closes the expression (required!)

SQL evaluates the WHEN branches top to bottom and returns the value of the first one that is true.

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

All lessons in this course

  1. The CASE Expression
  2. Searched vs Simple CASE
  3. Bucketing and Labeling Data
  4. CASE in ORDER BY and Aggregates
← Back to SQL Academy