Conditional Functions (scalar functions)

Part of the datafusion-spark function reference.

if

Returns expr1 if cond is true, and expr2 otherwise. A NULL condition counts as false. It is rewritten to CASE WHEN cond THEN expr1 ELSE expr2 END, so an error such as division by zero in the branch that isn't taken is not raised. expr1 and expr2 are coerced to a common type (if(true, 10, 20.5) returns a DOUBLE). It is an error if cond is not a boolean or NULL. DataFusion has no built-in if.

if(cond, expr1, expr2)

Arguments

  • cond: Boolean expression. NULL is treated as false.
  • expr1: Expression returned when cond is true.
  • expr2: Expression returned when cond is false or NULL.

Example

> SELECT if(1 < 2, 'a', 'b');
a
> SELECT if(NULL, 'yes', 'no');
no
> SELECT if(true, 1 / 1, 1 / 0);
1

nanvl

Returns expr1 if it is not NaN, or expr2 if expr1 is NaN. Unlike DataFusion‘s built-in nanvl, which evaluates both arguments eagerly, this function only evaluates expr2 when expr1 is NaN, matching Spark’s short-circuiting behavior. If expr1 is NULL the result is NULL, even when expr2 is not NULL; a NULL expr2 only matters when expr1 is NaN. Both arguments are implicitly cast to DOUBLE (integer, DECIMAL and STRING arguments included); if both arguments are FLOAT the result is FLOAT, otherwise the result is DOUBLE. +/-Infinity and -0.0 are not NaN and are returned unchanged, with the sign of zero preserved.

nanvl(expr1, expr2)

Arguments

  • expr1: Numeric expression, cast to DOUBLE (or FLOAT if both arguments are FLOAT). NULL returns NULL regardless of expr2.
  • expr2: Numeric expression, cast to match expr1. Only evaluated, and only matters, when expr1 is NaN.

Example

> SELECT nanvl(cast('NaN' as double), 123);
123
> SELECT nanvl(5.0, CAST(NULL AS DOUBLE));
5
> SELECT nanvl(CAST(NULL AS DOUBLE), 5.0);
NULL
> SELECT nanvl(CAST('NaN' AS DOUBLE), CAST('NaN' AS DOUBLE));
NaN