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.

  • ELSE is 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)


Result:

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

  1. CASE returns a value based on conditions.

  2. Can be used in SELECT, UPDATE, ORDER BY, or WHERE clauses.

  3. Supports Simple CASE (exact match) and Searched CASE (conditions).

  4. ELSE provides a default value if no condition matches; otherwise returns NULL.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *