capypad
0 day streak
sql / intermediate
Snippet

Conditional Logic with CASE

The CASE expression allows you to add conditional logic to your SQL queries. It evaluates conditions and returns a value when the first condition is met (like an if-then-else statement).

snippet.sql
sql
1
2
3
4
5
6
7
SELECT product_name,
CASE
WHEN stock_count > 100 THEN 'High Stock'
WHEN stock_count > 0 THEN 'Low Stock'
ELSE 'Out of Stock'
END AS inventory_status
FROM warehouse;
Breakdown
1
CASE
Starts the conditional block.
2
WHEN stock_count > 100 THEN 'High Stock'
Checks the first condition; if true, returns the specified string.
3
ELSE 'Out of Stock'
Provides a default value if none of the previous conditions were met.
4
END AS inventory_status
Closes the CASE block and assigns an alias to the resulting column.