The MySQL CASE expression adds if / else if / else branching directly inside SQL queries. You can use CASE to bucket numbers into tiers, build pivot-style counts, or customize sort order without post-processing rows in application code.
Searched CASE evaluates general boolean conditions (WHEN price >= 100), while Simple CASE compares one expression against fixed values (CASE status WHEN 'paid'). Searched CASE is more flexible because it supports ranges and IS NULL:
SELECT
product_name,
price,
CASE
WHEN price >= 200 THEN 'Premium'
WHEN price >= 50 THEN 'Standard'
ELSE 'Budget'
END AS price_tier
FROM demo_products;
This query groups demo_products into price tiers and counts how many products fall into each bucket:
SELECT
CASE
WHEN price >= 200 THEN 'Premium'
WHEN price >= 50 THEN 'Standard'
ELSE 'Budget'
END AS price_tier,
COUNT(*) AS product_count
FROM demo_products
GROUP BY price_tier
ORDER BY product_count DESC;
| price_tier | product_count |
|---|---|
| Standard | 9 |
| Budget | 7 |
| Premium | 4 |
You can also use CASE inside ORDER BY to pin urgent rows at the top of a queue:
SELECT id, status, total_amount
FROM demo_orders
ORDER BY
CASE status
WHEN 'on_hold' THEN 1
WHEN 'pending' THEN 2
ELSE 3
END,
id DESC;
ELSE: Without an ELSE branch, unmatched rows evaluate to NULL, which can break downstream math or API formatting. Supply a clear default string or zero fallback.CASE stops at the first true WHEN branch. Put WHEN score >= 90 before WHEN score >= 70, otherwise higher numbers match the looser branch early.CASE Expressions or Use a CTE: To reuse a computed CASE label in WHERE or multiple calculations, wrap it inside a CTE first.CASE inside UPDATE statements?Yes, UPDATE demo_products SET price = CASE WHEN category = 'Books' THEN price * 1.05 ELSE price END; updates multiple tiers in one query.
CASE portable outside MySQL?Yes, CASE ... WHEN ... THEN ... ELSE ... END is ANSI SQL standard and works identically in PostgreSQL, SQLite, and SQL Server.
CASE status WHEN NULL runs?In simple CASE, status = NULL is always unknown and never matches! Use searched CASE WHEN status IS NULL THEN ... instead.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.