MySQL CASE WHEN statement is a conditional expression that evaluates a set of conditions and returns a value based on the result of the evaluation. The syntax is as follows:
SELECT
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END AS column_alias
FROM table_name;
The conditions can be any logical expression that evaluates to true or false, such as comparisons (>, <, =), functions (LIKE, IN), or other operators (AND, OR). The results can be any data type, including strings, numbers, or NULL.
Here’s an example of using the CASE WHEN statement to categorize products by price:
SELECT product_name,
CASE
WHEN price <= 10 THEN 'Low'
WHEN price > 10 AND price <= 20 THEN 'Medium'
WHEN price > 20 THEN 'High'
END AS price_category
FROM products;
This query will return a list of product names with their corresponding price categories (Low, Medium, or High), based on the price ranges defined in the CASE WHEN statement.