MySQL CASE Statement
The CASE
statement in MySQL is used for conditional logic. It evaluates a series of conditions and returns a value when the first condition is met. If no conditions are true, an optional ELSE
value is returned. The CASE
statement can be used in SQL queries, stored procedures, and functions.
Syntax
Simple CASE
expression
: The value or column being compared.value1
,value2
, etc.: The values to compare theexpression
against.result1
,result2
, etc.: The values returned when a match is found.default_result
: The value returned if no match is found (optional).
Searched CASE
condition1
,condition2
, etc.: Conditions evaluated in sequence.result1
,result2
, etc.: The values returned when a condition evaluates to true.default_result
: The value returned if no conditions are true (optional).
Key Features
- Flexibility: Can evaluate expressions or conditions.
- Return Type: The
CASE
statement returns a single value. - Optional ELSE: If
ELSE
is omitted and no condition matches,NULL
is returned. - Usable in Queries: Commonly used in
SELECT
,WHERE
,ORDER BY
, and other SQL clauses.
Examples
1. Simple CASE in SELECT
Result
employee_id | first_name | department_name |
---|---|---|
101 | John | HR |
102 | Sarah | Finance |
103 | Mike | Unknown |
2. Searched CASE in SELECT
Result
employee_id | first_name | salary | salary_category |
---|---|---|---|
101 | John | 120000 | High |
102 | Sarah | 75000 | Medium |
103 | Mike | 40000 | Low |
3. Using CASE in WHERE
4. CASE in ORDER BY
Result
The rows will be sorted as High
→ Medium
→ Low
.
5. CASE with Aggregation
Result
department | total_employees |
---|---|
HR | 5 |
Finance | 8 |
Others | 12 |
Key Notes
- Default Value: If no condition matches and no
ELSE
is provided,NULL
is returned. - Nested CASE: You can nest
CASE
statements to handle complex logic. - NULL Handling: Be cautious when comparing
NULL
values. UseIS NULL
instead of=
for comparisons.
Practical Use Cases
- Categorize Data: Categorizing employees, products, or transactions based on conditions.
- Conditional Aggregation: Applying conditional logic within aggregation functions like
SUM
orCOUNT
. - Dynamic Filtering: Writing flexible
WHERE
clauses for queries.
Performance Tips
- Index Usage: Avoid using
CASE
inWHERE
orJOIN
clauses when possible, as it can prevent MySQL from using indexes efficiently. - Simplify Logic: For complex
CASE
statements, try to break them into smaller pieces or use temporary tables for better readability.
Conclusion
The CASE
statement is a versatile tool for handling conditional logic directly within SQL. It simplifies complex queries and enhances their readability and functionality. Whether you're categorizing data or applying dynamic conditions, CASE
provides a clean and powerful solution.
Let me know if you'd like further examples or assistance!