MySQL CASE Expression
The
CASE
expression in MySQL is a conditional expression that allows you to return different values based on conditions, similar to IF-ELSE
logic.1. MySQL CASE Syntax
Simple CASE Expression
Used when comparing a column/variable to multiple values.
Searched CASE Expression
Used when evaluating complex conditions.
2. Using CASE in SELECT Statement
Example 1: Categorizing Employees by Salary
✅ Output:
name | salary | salary_category |
---|---|---|
John | 12000 | High |
Alice | 7000 | Medium |
Bob | 3000 | Low |
3. Using CASE in ORDER BY
Example 2: Ordering Products Based on Stock Status
✅ Orders products with out-of-stock items first, low-stock next, and in-stock last.
4. Using CASE in UPDATE Statement
Example 3: Updating Employee Bonus Based on Performance
✅ Assigns a bonus percentage based on employee performance.
5. Using CASE in GROUP BY
Example 4: Counting Employees in Different Age Groups
✅ Output:
age_group | total |
---|---|
Young | 5 |
Mid-age | 12 |
Senior | 8 |
6. Using CASE with Aggregate Functions
Example 5: Calculating Total Sales for Different Categories
✅ Calculates total sales per category.
7. Using CASE in HAVING Clause
Example 6: Filtering Customers Based on Order Value
✅ Filters customers who spent more than $500.
8. MySQL CASE with NULL Values
Example 7: Handling NULL in CASE
✅ Replaces NULL values with "No Email"
in the result.
9. Conclusion
Use Case | Example |
---|---|
Categorizing Data | SELECT name, CASE WHEN salary > 5000 THEN 'High' ELSE 'Low' END FROM employees; |
Conditional Sorting | ORDER BY CASE WHEN stock = 0 THEN 1 ELSE 2 END; |
Updating Data Based on Condition | UPDATE employees SET bonus = CASE WHEN rating = 'A' THEN 1000 ELSE 500 END; |
Filtering with Aggregate Functions | HAVING CASE WHEN SUM(sales) > 500 THEN 1 ELSE 0 END = 1; |
š Master MySQL CASE expressions to write dynamic queries!