CASE...WHEN
Function
CASE...WHEN is a conditional expression used to return different values based on conditions. Spark SQL supports two forms: the simple CASE function and the CASE search function.
Syntax
Simple CASE function: Jumps to the corresponding result1 based on the match between expression and value1.
CASE expression WHEN value1 THEN result1 [ WHEN value2 THEN result2 ] ... [ ELSE else_result ] END
CASE search function: Evaluates condition1 for each WHEN clause in the specified order. Returns result1 for the first condition1 that evaluates to TRUE.
CASE WHEN condition1 THEN result1 [ WHEN condition2 THEN result2 ] ... [ ELSE else_result ] END
Parameters
| Parameter | Description |
|---|---|
| expression | The expression being compared in the simple CASE. |
| WHEN value | In the simple CASE, returns the corresponding THEN result when expression equals value. |
| WHEN condition | In the CASE search function, returns the corresponding THEN result when condition is true. |
| THEN result | The result returned when the condition is met. The types of all THEN results should be consistent. |
| ELSE else_result | The result returned when none of the WHEN conditions are met. If ELSE is omitted, NULL is returned. |
Precautions
- The simple CASE function uses equality comparison (=), while the CASE search function supports any Boolean condition.
- The CASE expression evaluates conditions from top to bottom and returns the THEN result of the first satisfied condition. Subsequent conditions are not evaluated.
- The types of all THEN and ELSE return values should be consistent or implicitly convertible.
- CASE expressions can be used in any place where an expression is needed, such as the SELECT list, WHERE conditions, ORDER BY, GROUP BY, etc.
Examples
- Simple CASE function:
Returns the name field from the student table and a string corresponding to class_id.
SELECT name, CASE class_id WHEN 1 THEN 'Class A' WHEN 2 THEN 'Class B' WHEN 3 THEN 'Class C' ELSE 'Other' END AS class_name FROM student; - CASE search function:
Queries the student table, returning the name field and a result corresponding to score. Returns EXCELLENT if score >= 90, GOOD if 80 < score < 90, and BAD otherwise.
SELECT name, CASE WHEN score >= 90 THEN 'EXCELLENT' WHEN 80 < score AND score < 90 THEN 'GOOD' ELSE 'BAD' END AS level FROM student;
- CASE used in ORDER BY:
SELECT name, score FROM student ORDER BY CASE WHEN score >= 60 THEN 0 ELSE 1 END, score DESC;
- CASE used in aggregation:
SELECT class_id, COUNT(CASE WHEN score >= 90 THEN 1 END) AS excellent_count, COUNT(CASE WHEN score < 60 THEN 1 END) AS fail_count FROM student GROUP BY class_id;
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot