Featured Article

Master PySpark SQL CASE WHEN with Practical Examples

Kenneth Jul 13, 2026

Pyspark SQL's case when statement is a powerful tool for conditional processing, enabling you to define different actions based on data characteristics. By leveraging this functionality, you can streamline data transformations, perform complex calculations, and create more efficient Spark SQL operations.

SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial

In this comprehensive guide, we will delve into the intricacies of Pyspark SQL's case when example, providing a step-by-step approach to understand and implement it effectively. Mastering case when in Pyspark SQL will not only enhance your skills but also boost the efficiency of your data processing tasks.

SQL CTE Explained with Examples | Common Table Expression Tutorial
SQL CTE Explained with Examples | Common Table Expression Tutorial

Understanding Case When in PySpark SQL

Before exploring the Pyspark SQL case when example, let's first understand the basics of case when. It is a SQL construct that allows you to evaluate different expressions based on specified conditions. In PySpark, you can integrate case when statements into your DataFrame and Dataset APIs for data manipulation.

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

Case when follows a simple syntax: `CASE WHEN condition1 THEN result1 ELSE result2 END`. It provides a flexible way to handle conditions where the output depends on various data values. Now, let's dive into PySpark SQL case when examples to illustrate its usage effectively.

Basic Case When in PySpark SQL

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

Let's begin with a basic case when in PySpark SQL. Consider a DataFrame containing an 'Age' column. We want to categorize individuals into 'Minor', 'Adult', or 'Senior' based on their age. Here's how you can achieve this:

from pyspark.sql import functions as F

df = spark.createDataFrame([(15,), (25,), (65,)], ['Age'])

df.withColumn('Category',
               F.when(F.col('Age') < 18, 'Minor')
               .when(F.col('Age') < 60, 'Adult')
               .otherwise('Senior')).show()

In this Pyspark SQL case when example, we used the DataFrame's withColumn function in conjunction with PySpark's when and otherwise functions to create a new 'Category' column based on the defined conditions.

Nested Case When in PySpark SQL

Top 10 SQL Queries Every Data Analyst Must Know in 2026
Top 10 SQL Queries Every Data Analyst Must Know in 2026

In some scenarios, you might need to nest case when statements to create complex conditional expressions. Let's extend the previous example to create an additional 'Discount' column based on the 'Category' and 'Age' columns.

df = df.withColumn('Discount',
                   F.when(F.col('Category') == 'Minor', F.lit(20))
                   .when(F.col('Age') >= 60, F.lit(15))
                   .otherwise(F.lit(0))).show()

In this nested case when example, we first checked the 'Category'. If it's 'Minor', we applied a 20% discount. If not, we then checked the 'Age'. If it's 60 or above, we applied a 15% discount. If none of the conditions were met, we applied a 0% discount.

Case When with If and Elseif Conditions

SQL NULLIF() Explained with Examples | Prevent Divide by Zero Errors in SQL
SQL NULLIF() Explained with Examples | Prevent Divide by Zero Errors in SQL

In some cases, you might want to use multiple conditions with 'if-elseif' logic instead of the nested case when approach. PySpark SQL provides the `F.expr` function to achieve this. Let's create a DataFrame with 'Income' and 'Student' columns, and calculate 'Tax' based on income and student status.

For non-students, we'll apply a graduated tax rate: no tax for income up to $20,000, 10% for income between $20,000 and $50,000, and 20% for income over $50,000. For students, the tax rate will be 5% for all incomes.

Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
SQL Cheat Sheet: 9 Must-Know Concepts for Beginners & Interviews
SQL Cheat Sheet: 9 Must-Know Concepts for Beginners & Interviews
SQL Cheat Sheet in 60 seconds 👇
SQL Cheat Sheet in 60 seconds 👇
SQL Essentials Cheat Sheet | The Only SQL Notes You'll Need for Revision
SQL Essentials Cheat Sheet | The Only SQL Notes You'll Need for Revision
There are three types of window function families 🏠
There are three types of window function families 🏠
PySpark “when otherwise” usage with example
PySpark “when otherwise” usage with example
SQL HAVING CLAUSE explained for beginners
SQL HAVING CLAUSE explained for beginners
SQL Joins Explained with Examples | Complete JOIN Cheat Sheet for Beginners
SQL Joins Explained with Examples | Complete JOIN Cheat Sheet for Beginners

Creating Custom Conditions with 'if-elseif'

To implement this in PySpark SQL, we'll use 'if-elseif' logic with the `F.expr` function:

df = spark.createDataFrame([(15000, False), (40000, True), (70000, False)], ['Income', 'Student'])

df.withColumn('Tax',
              F.expr("""
                      CASE
                      WHEN Student THEN Income*0.05
                      WHEN Income <= 20000 THEN 0
                      WHEN Income <= 50000 THEN Income*0.1
                      ELSE Income*0.2
                      END
                     """)).show()

In this Pyspark SQL case when example, we created a custom case when statement with multiple conditions using 'if-elseif' logic to calculate the 'Tax' column.

Case When with User-Defined Functions (UDFs)

Sometimes, you might need to use case when in conjunction with user-defined functions (UDFs) to create more complex conditional expressions. To illustrate this, let's create a UDF to categorize 'Income' into 'Low', 'Medium', or 'High' based on defined thresholds.

We'll then use this UDF within a case when statement to create a new 'Tax_Step' column. For 'Low' income, the tax rate is 0%; for 'Medium', it's 10%; and for 'High', it's 20%.

Creating UDFs for Complex Case When Expressions

from pyspark.sql.functions import udf
from pyspark.sql.types import StringType

@udf(returnType=StringType())
def income_category(income):
    if income <= 20000:
        return 'Low'
    elif income <= 50000:
        return 'Medium'
    else:
        return 'High'

df = df.withColumn('Income_Category', income_category('Income')) \
       .withColumn('Tax_Step',
                   F.expr("""
                           CASE
                           WHEN Income_Category = 'Low' THEN Income*0.0
                           WHEN Income_Category = 'Medium' THEN Income*0.1
                           ELSE Income*0.2
                           END
                          """)).show()

In this Pyspark SQL case when example, we first created a UDF to categorize income. We then used this UDF within another case when statement to calculate the 'Tax_Step' column based on the income category.

Mastering Pyspark SQL's case when statements allows you to create complex conditional logic easily, enhancing your data processing capabilities. By understanding the basics and exploring various use cases, you can efficiently handle data transformation tasks and optimize your PySpark workflows. Embrace the power of case when and continue exploring the riches of PySpark SQL functionality to unleash your data processing potential.