You are viewing documentation about an older version (1.3.0). View latest version

snowflake.snowpark.functions.when¶

snowflake.snowpark.functions.when(condition: ColumnOrSqlExpr, value: ColumnOrLiteral) → CaseExpr[source]¶

Works like a cascading if-then-else statement. A series of conditions are evaluated in sequence. When a condition evaluates to TRUE, the evaluation stops and the associated result (after THEN) is returned. If none of the conditions evaluate to TRUE, then the result after the optional OTHERWISE is returned, if present; otherwise NULL is returned.

Parameters:
  • condition – A Column expression or SQL text representing the specified condition.

  • value – A Column expression or a literal value, which will be returned if condition is true.

Example:

>>> df = session.create_dataframe([1, None, 2, 3, None, 5, 6], schema=["a"])
>>> df.collect()
[Row(A=1), Row(A=None), Row(A=2), Row(A=3), Row(A=None), Row(A=5), Row(A=6)]
>>> df.select(when(col("a") % 2 == 0, lit("even")).as_("ans")).collect()
[Row(ANS=None), Row(ANS=None), Row(ANS='even'), Row(ANS=None), Row(ANS=None), Row(ANS=None), Row(ANS='even')]
Copy

Multiple when statements can be changed and otherwise/else_ used to create expressions similar to CASE WHEN ... ELSE ... END in SQL.

Example:

>>> df.select(when(col("a") % 2 == 0, lit("even")).when(col("a") % 2 == 1, lit("odd")).as_("ans")).collect()
[Row(ANS='odd'), Row(ANS=None), Row(ANS='even'), Row(ANS='odd'), Row(ANS=None), Row(ANS='odd'), Row(ANS='even')]
>>> df.select(when(col("a") % 2 == 0, lit("even")).when(col("a") % 2 == 1, lit("odd")).otherwise(lit("unknown")).as_("ans")).collect()
[Row(ANS='odd'), Row(ANS='unknown'), Row(ANS='even'), Row(ANS='odd'), Row(ANS='unknown'), Row(ANS='odd'), Row(ANS='even')]
Copy