Conditional logic is everywhere—from setting discounts to classifying users. SQL has a native way to handle this with the CASE
statement.
In this quick guide, you’ll explore how to use CASE
to implement branching logic in your queries. We’ll cover its two forms, show real-world use cases, and explain where and when to use it for best results.
Using SQL CASE in Practice
Simple comparison:
CASE grade
WHEN 'A' THEN 'Excellent'
WHEN 'B' THEN 'Good'
ELSE 'Needs Work'
END
Conditional logic for prices:
CASE
WHEN category = 'Shoes' THEN price * 0.85
WHEN category = 'Gifts' AND price <= 50 THEN price * 0.5
ELSE price
END
Employee bonus example:
CASE
WHEN role = 'Manager' AND years >= 5 THEN salary * 0.1
WHEN role = 'Developer' AND years >= 3 THEN salary * 0.08
ELSE 0
END
Used in WHERE clause:
WHERE
CASE
WHEN status = 'active' THEN 1
ELSE 0
END = 1
FAQ
How does the CASE statement work in SQL?
It evaluates conditions in order and returns the result of the first match.
Can I use CASE in ORDER BY?
Yes. You can use it for sorting rows based on dynamic logic.
Is ELSE required?
No. But without it, unmatched conditions return NULL
.
Can I nest CASE statements?
Yes. Nesting allows more complex logic handling in a single query.
Conclusion
The SQL CASE
statement is powerful for applying conditional logic in queries—no external scripts or procedural code needed. It’s supported in all major databases and flexible enough for many use cases.
Read the full guide SQL CASE Statement: Definitive Guide.
Top comments (0)