MySQL CASE Statement
MySQL CASE Statement
The CASE statement in MySQL is used to return conditional values in a query.
It works like an IF-THEN-ELSE statement and is commonly used in SELECT, UPDATE, or ORDER BY clauses.
🔹 Syntax (Simple CASE)
-
Compares a column to specific values.
-
Returns the corresponding result.
-
ELSEis optional; if not specified, it returns NULL.
🔹 Syntax (Searched CASE)
-
Evaluates conditions instead of exact values.
-
More flexible than simple CASE.
🧠Example Table: students
| id | name | marks |
|---|---|---|
| 1 | John | 85 |
| 2 | Emma | 90 |
| 3 | Raj | 76 |
| 4 | Sara | 92 |
| 5 | Aman | 60 |
🔹 Example 1: Assign Grades (Simple CASE)
| name | marks | Grade |
|---|---|---|
| John | 85 | A |
| Emma | 90 | A+ |
| Raj | 76 | B |
| Sara | 92 | C |
| Aman | 60 | C |
🔹 Example 2: Assign Grades (Searched CASE)
Result:
| name | marks | Grade |
|---|---|---|
| John | 85 | A |
| Emma | 90 | A+ |
| Raj | 76 | B |
| Sara | 92 | A+ |
| Aman | 60 | C |
✅ Notice: The searched CASE evaluates ranges using conditions.
🔹 Key Points
-
CASE returns a value based on conditions.
-
Can be used in SELECT, UPDATE, ORDER BY, or WHERE clauses.
-
Supports Simple CASE (exact match) and Searched CASE (conditions).
-
ELSEprovides a default value if no condition matches; otherwise returns NULL.
