In MySQL, the CASE statement allows you to perform conditional logic within a SQL query. It's useful for tasks like data transformation, categorization, and generating calculated fields based on conditions.
Here's the basic syntax for a simple CASE statement:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END
And here's the syntax for a searched CASE statement, which evaluates each condition independently:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END
Here's an example to illustrate the usage of the CASE statement:
Suppose you have a table named employees with columns employee_id, first_name, last_name, and salary. You want to create a new column called salary_category, which categorizes employees based on their salary into three categories: "Low", "Medium", and "High".
SELECT
employee_id,
first_name,
last_name,
salary,
CASE
WHEN salary < 50000 THEN 'Low'
WHEN salary >= 50000 AND salary < 100000 THEN 'Medium'
ELSE 'High'
END AS salary_category
FROM employees;
In this example, the CASE statement categorizes employees based on their salary into "Low", "Medium", or "High" categories. The result set includes the original columns from the employees table along with the newly created salary_category column.