MySQL Tutorial
CASE StatementThe 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.
we have 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 |
CASE expression WHEN value1 THEN result1 WHEN value2 THEN result2 ELSE default_result END
We can calculate grades using a Simple CASE statement based on the student’s score.
Try it yourself
|
name |
score |
grade |
|---|---|---|
|
Alice |
85 |
F |
|
Bob |
75 |
F |
|
Charlie |
95 |
A+ |
|
David |
65 |
F |
|
Eve |
80 |
B |
|
Frank |
90 |
A |
|
Alice |
60 |
D |
CASE score directly compares the score column with the specified values.score.ELSE clause returns 'F'.CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE default_result END
We can calculate grades based on student scores using CASE.
Try it yourself
|
name |
score |
grade |
|---|---|---|
|
Alice |
85 |
B |
|
Bob |
75 |
C |
|
Charlie |
95 |
A |
|
David |
65 |
D |
|
Eve |
80 |
B |
|
Frank |
90 |
A |
|
Alice |
60 |
D |
CASE checks the score and assigns a grade.NULL is treated as not matching any condition, so it defaults to 'F'.