CASE Expression
1. Overview
The CASE expression is a conditional selection structure in SQL that allows returning different results based on a series of conditions. There are two forms of CASE expressions: expression-based CASE and condition-based CASE. Both can be used to implement branching logic in queries.
2. Expression-based CASE
Syntax:
Features:
- Returns the corresponding result
resNwhen the expressionexpris equal tooptN. - If
expris not equal to anyoptN, returns the default valuedef. Ifdefis not specified, returnsnull.
Parameters:
expr: An expression of any type to be compared.optN: A conditional expression of the same type asexprfor comparison.resN: The result expression returned when the condition matches.def: The default result expression when no conditions match.
Example:
Result:
3. CASE Based on Conditions
Syntax:
Functionality:
- When the condition
condNistrue, the corresponding resultresNis returned. - If none of the conditions are met, the default value
defis returned. Ifdefis not specified,nullis returned.
Parameters:
condN: Boolean expression used to determine if the branch condition is met.resN: The result expression returned when the condition is met.def: The default result expression when no conditions are met.
Example:
Result:
4. Application Scenarios
- Data Transformation: Transform or map data based on different conditions.
- Group Statistics: Classify and summarize data based on certain conditions during group statistics.
- Query Optimization: Filter or select the required data based on conditions during the query process.
5. Precautions
- Ensure that the data types of
resNanddefare consistent. - When using condition-based CASE expressions, ensure that all conditions are mutually exclusive to avoid ambiguity.
- In practical applications, choose the appropriate form of CASE expression based on specific needs.
