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(“user.name”)

import org.apache.spark.sql.SparkSession

val username = System.getProperty(“user.name”)

val spark = SparkSession.

builder.

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

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

enableHiveSupport.

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

master("yarn").

getOrCreate 

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:

SELECT 
    CASE 
        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
LIMIT 10

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.

Conclusion
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