The IF and CASE statements in MySQL are used for conditional logic inside SQL queries. They help return different results based on conditions and are widely used to implement business rules directly in the database.
// IF function checks a condition and returns one of two values
IF(condition, true_value, false_value)
// Classify products as expensive or cheap based on price
SELECT product_name,
IF(price > 1000, 'expensive', 'cheap') AS price_category
FROM products;
// CASE evaluates multiple conditions sequentially
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
END
// Categorize products into multiple price ranges
SELECT product_name,
CASE
WHEN price > 1000 THEN 'expensive'
WHEN price BETWEEN 500 AND 1000 THEN 'moderate'
ELSE 'cheap'
END AS price_category
FROM products;
The query categorizes products based on price and returns labels such as expensive, moderate, or cheap depending on which condition matches.