Advertisement
Google Ad Slot: content-top
MySQL CASE
MySQL CASE Statement
The CASE statement in MySQL is used to perform conditional logic in SQL queries, similar to IF-ELSE statements in programming. It evaluates conditions and returns a result based on the first condition that evaluates to TRUE.
Types of CASE Statements
- Simple CASE → Compares a single expression to multiple values.
- Searched CASE → Evaluates multiple conditions with logical expressions.
we have students table
students table
student_id |
name |
gender |
city |
age |
score |
course_id |
phone_number |
|
|---|---|---|---|---|---|---|---|---|
1 |
Alice |
Female |
Delhi |
20 |
85 |
101 |
NULL |
1234567890 |
2 |
Bob |
Male |
Mumbai |
22 |
75 |
NULL |
bob@email.com |
NULL |
3 |
Charlie |
Male |
Delhi |
21 |
95 |
102 |
NULL |
NULL |
4 |
David |
Male |
Bangalore |
23 |
65 |
101 |
david@email.com |
NULL |
5 |
Eve |
Female |
Mumbai |
20 |
80 |
103 |
NULL |
NULL |
6 |
Frank |
Male |
Delhi |
22 |
90 |
103 |
NULL |
NULL |
7 |
Alice |
Female |
Mumbai |
19 |
60 |
102 |
NULL |
NULL |
1. Simple CASE Statement
Syntax:
CASE expression WHEN value1 THEN result1 WHEN value2 THEN result2 ELSE default_result END
Example
We can calculate grades using a Simple CASE statement based on the student’s score.
Output:
name |
score |
grade |
|---|---|---|
Alice |
85 |
F |
Bob |
75 |
F |
Charlie |
95 |
A+ |
David |
65 |
F |
Eve |
80 |
B |
Frank |
90 |
A |
Alice |
60 |
D |
Explanation:
CASE scoredirectly compares thescorecolumn with the specified values.- It returns the matching grade based on the value of
score. - If no match is found, the
ELSEclause returns'F'.
2. Searched CASE Statement
Syntax:
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE default_result END
Example:
We can calculate grades based on student scores using CASE.
Output:
name |
score |
grade |
|---|---|---|
Alice |
85 |
B |
Bob |
75 |
C |
Charlie |
95 |
A |
David |
65 |
D |
Eve |
80 |
B |
Frank |
90 |
A |
Alice |
60 |
D |
Explanation:
CASEchecks thescoreand assigns a grade.NULLis treated as not matching any condition, so it defaults to'F'.