SQL
Conditional Logic in SQL Queries with CASE WHEN
Implement powerful conditional logic directly within your SQL queries using the CASE WHEN statement. This enables dynamic result sets or updates based on various criteria.
SELECT product_name, price,
CASE
WHEN price > 100 THEN 'Expensive'
WHEN price BETWEEN 50 AND 100 THEN 'Mid-range'
ELSE 'Affordable'
END AS price_category
FROM products;
How it works: The `CASE WHEN` statement allows you to apply conditional logic within your SQL queries, similar to if-else statements in programming. It evaluates conditions and returns a corresponding value, enabling you to create dynamic columns or update records based on complex criteria. This snippet categorizes products based on their price, returning a descriptive string for each category.