SQL
Implement Conditional Logic with SQL CASE Statements
Dynamically categorize or transform data within your SQL queries based on specified conditions, similar to 'if-else' statements, for flexible data presentation.
SELECT
product_name,
price,
CASE
WHEN price >= 100 THEN 'Premium'
WHEN price BETWEEN 50 AND 99.99 THEN 'Mid-Range'
ELSE 'Budget'
END AS price_category
FROM products
ORDER BY price DESC;
How it works: The SQL `CASE` statement allows you to implement conditional logic directly within your queries, much like if-else statements in programming languages. This snippet categorizes products into 'Premium', 'Mid-Range', or 'Budget' based on their price. Each `WHEN` condition is evaluated in order, and the first true condition's `THEN` value is returned. If no `WHEN` condition is met, the `ELSE` value is used. This is incredibly useful for creating custom labels, calculations, or ordering based on specific criteria.