MySQL CASE Expression
MySQL CASE Expression: Conditional Logic in SQL
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.
Two Forms of CASE Syntax
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;
Practical SQL Examples
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;
Common Mistakes and Best Practices
- Always Include
ELSE: Without anELSEbranch, unmatched rows evaluate toNULL, which can break downstream math or API formatting. Supply a clear default string or zero fallback. - Order Conditions Most Specific First:
CASEstops at the first trueWHENbranch. PutWHEN score >= 90beforeWHEN score >= 70, otherwise higher numbers match the looser branch early. - Repeat
CASEExpressions or Use a CTE: To reuse a computedCASElabel inWHEREor multiple calculations, wrap it inside a CTE first.
Frequently Asked Questions
Can I use 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.
Is CASE portable outside MySQL?
Yes, CASE ... WHEN ... THEN ... ELSE ... END is ANSI SQL standard and works identically in PostgreSQL, SQLite, and SQL Server.
What happens if 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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.