Data Engineering Spark SQL - Spark SQL Functions - Using CASE and WHEN

At times we might have to select values from multiple columns conditionally. Let us start spark context for this Notebook so that we can execute the code provided. You can sign up for our 10 node state of the art cluster/labs to learn Spark SQL using our unique integrated LMS.

val username = System.getProperty(“”)

import org.apache.spark.sql.SparkSession

val username = System.getProperty(“”)

val spark = SparkSession.


config("spark.ui.port", "0").

config("spark.sql.warehouse.dir", s"/user/${username}/warehouse").


appName(s"${username} | Spark SQL - Predefined Functions").



If you are going to use CLIs, you can use Spark SQL using one of the 3 approaches.

Using Spark SQL

spark2-sql \
    --master yarn \
    --conf spark.ui.port=0 \
    --conf spark.sql.warehouse.dir=/user/${USER}/warehouse

Using Scala

spark2-shell \
    --master yarn \
    --conf spark.ui.port=0 \
    --conf spark.sql.warehouse.dir=/user/${USER}/warehouse

Using Pyspark

pyspark2 \
    --master yarn \
    --conf spark.ui.port=0 \
    --conf spark.sql.warehouse.dir=/user/${USER}/warehouse
  • We can use CASE and WHEN for that.
  • Let us implement this conditional logic to come up with derived order_status.
    • If order_status is COMPLETE or CLOSED, set COMPLETED
    • If order_status have PENDING in it, then we will say PENDING
    • If order_status have PROCESSING or PAYMENT_REVIEW in it, then we will say PENDING
    • We will set all others as OTHER
  • We can also have ELSE as part of CASE and WHEN.

Key Concepts Explanation

Applying CASE and WHEN

This concept involves using CASE and WHEN statements in SQL to perform conditional transformations on data. Here is an example:

        WHEN order_status IN ('COMPLETE', 'CLOSED') THEN 'COMPLETED'
        WHEN order_status LIKE '%PENDING%' OR order_status IN ('PROCESSING', 'PAYMENT_REVIEW') THEN 'PENDING'
        ELSE 'OTHER'
    END AS updated_order_status
FROM orders

Hands-On Tasks

  1. Use CASE and WHEN to create a new column based on conditional logic for order status.
  2. Practice different combinations of conditions using CASE and WHEN statements.

In this article, we learned how to use CASE and WHEN statements in SQL to perform conditional transformations on data. It is a powerful tool for deriving new columns based on specific conditions in the dataset. Practice and experiment with different scenarios to master this concept.

Watch the video tutorial here