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 branchesELSE value— an optional fallbackEND— 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