Featured Article

Master PySpark SQL WHEN Function for Conditional Logic

Kenneth Jul 13, 2026

To harness the full power of Apache Spark's DataFrames and Datasets, it's crucial to understand and utilize its built-in functions. One of the most versatile functions is the when function, particularly useful when you want to conditionally apply transformations to your data. In this guide, we'll delve into the from pyspark.sql.functions import when syntax and explore its applications with practical examples.

PySpark DataFrame Transformations: select vs withColumn
PySpark DataFrame Transformations: select vs withColumn

The when function allows you to specify a condition and a resulting value. If the condition is true, it returns the specified value; otherwise, it returns null or another specified value. It's like a conditional statement in SQL, encapsulated within a function for an elegant, readable DataFrames API.

There are three types of window function families 🏠
There are three types of window function families 🏠

Understanding the when Function Syntax

Before we dive into examples, let's understand the syntax of the when function:

a cell phone with the text postgresql and other information on it
a cell phone with the text postgresql and other information on it

when(condition, value_if_true)

Optionally, a otherwise(value_if_false) clause can be appended for specifying a value to return when the condition is false:

SQL String Functions and Pattern Matching
SQL String Functions and Pattern Matching

when(condition, value_if_true).otherwise(value_if_false)

Basic Usage of when

Let's start with a simple example. Suppose we have a DataFrame df with a column age, and we want to categorize 'adults' as those over 18:

SQL in 60 days
SQL in 60 days

```python from pyspark.sql.functions import when df = df.withColumn("categorized", when(col("age") > 18, "Adult").otherwise("Minor")) ```

Combining when with otherwise

We can also use the otherwise clause to categorize 'seniors' as those over 60:

```python df = df.withColumn("categorized", when(col("age") > 60, "Senior") .otherwise(when(col("age") > 18, "Adult") .otherwise("Minor"))) ```

Here, we're creating a new column called categorized that categorizes people based on their age.

7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio

Applying when in Filter Operations

The when function can also be used in filter operations to conditionally exclude or include rows based on specified conditions.

Transform Single Inputs into Tables Using PySpark UDTFs
Transform Single Inputs into Tables Using PySpark UDTFs
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
from pyspark sql functions import when
from pyspark sql functions import when
SQL Cheat Sheet in 60 seconds 👇
SQL Cheat Sheet in 60 seconds 👇
SQL Quick Notes Cheat Sheet | SQL Queries, Joins, Functions & Database Commands for Beginners
SQL Quick Notes Cheat Sheet | SQL Queries, Joins, Functions & Database Commands for Beginners
SQL Query Execution Order
SQL Query Execution Order
Understanding window functions in SQL
Understanding window functions in SQL
SQL Query Execution Order Explained | Logical Order of SQL Query Processing
SQL Query Execution Order Explained | Logical Order of SQL Query Processing

Filtering Data with when

Let's say we want to filter our DataFrame to show only adults and seniors. We can do this with the filter function and when:

```python adults_and_seniors = df.filter(when(col("categorized").isin(["Adult", "Senior"]), True).otherwise(False)) ```

Combining Conditions with and and or

The and and or functions can be used to combine conditions when using when:

```python adults_and_f Puis = df.filter((when(col("categorized").isin(["Adult", "Senior"]), True).otherwise(False)) & when(col("country") == "France", True)) ```

In this example, we're filtering for adults and seniors, and additionally only showing those from France.

Mastering the when function allows you to succinctly express complex conditional logic in your Spark data transformations and filtered operations. As your understanding deepens, you'll find it an invaluable tool in your Spark programming toolbox.

Practice with different datasets and edge cases to solidify your grasp on when. Explore other DataFrame and Dataset functions to expand your PySpark skillset. Happy coding!