snowflake.snowpark.functions.when(condition: Union[Column, str], value: Union[Column, None, bool, int, float, str, bytearray, Decimal, date, datetime, time, bytes, list, tuple, dict]) 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.

  • 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.


>>> 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)]
>>>"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')]

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


>>>"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')]
>>>"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')]