CASE
Published May 7, 2021Updated Jul 13, 2022
Contribute to Docs
The CASE
command is a logical test that returns different output based on the conditions of each statement and closes with an END
clause.
Syntax
CASE
WHEN this_condition THEN this_result
WHEN that_condition THEN that_result
ELSE fallback_result
END;
The result will come from the first WHEN .. THEN ...
statement that evaluates as “True”. If none of these statements are “True”, a fallback_result
from the ELSE
clause will be returned. If there is no ELSE
clause and none of the WHEN .. THEN ...
statements evaluate to “True”, NULL
is returned.
Example
The following example showcases the CASE
command returning output based on several conditions:
SELECT student_name AS 'Student',overall_gpa AS 'GPA',CASEWHEN overall_gpa > 3.0 THEN "Exceptional grades, keep up the good work!"WHEN overall_gpa BETWEEN 2.0 AND 3.0 THEN "Good job! Study hard this term!"ELSE "You're at risk of academic probation, seek help if needed."ENDFROM students;
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn SQL on Codecademy
- Skill path
Analyze Data with SQL
Learn to analyze data with SQL and prepare for technical interviews.Includes 9 CoursesWith CertificateBeginner Friendly17 hours - Skill path
Design Databases With PostgreSQL
Learn how to query SQL databases and design relational databases to efficiently store large quantities of data.Includes 5 CoursesWith CertificateBeginner Friendly13 hours - Free course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner Friendly5 hours