case expression
Applies to: Databricks SQL
Databricks Runtime
Returns resN for the first optN that equals expr or def if none matches.
Returns resN for the first condN evaluating to true, or def if none found.
Syntax
CASE expr {WHEN opt1 THEN res1} [...] [ELSE def] END
CASE {WHEN cond1 THEN res1} [...] [ELSE def] END
Arguments
expr: Any expression for which comparison is defined.optN: An expression that has a least common type withexprand all otheroptN.resN: Any expression that has a least common type with all otherresNanddef.def: An optional expression that has a least common type with allresN.condN: A BOOLEAN expression.
Returns
The result type matches the least common type of resN and def.
If def is omitted the default is NULL.
Conditions are evaluated in order and only the resN or def which yields the result is executed.
Examples
SQL
> SELECT CASE WHEN 1 > 0 THEN 1 WHEN 2 > 0 THEN 2.0 ELSE 1.2 END;
1.0
> SELECT CASE WHEN 1 < 0 THEN 1 WHEN 2 > 0 THEN 2.0 ELSE 1.2 END;
2.0
> SELECT CASE WHEN 1 < 0 THEN 1 WHEN 2 < 0 THEN 2.0 END;
NULL
> SELECT CASE 3 WHEN 1 THEN 'A' WHEN 2 THEN 'B' WHEN 3 THEN 'C' END;
C