Skip to main content
PYSPARK โ€ข LESSON 69

First Non-Null Selection with coalesce()

How do we select the first available phone number from mobile, home phone, or a fallback 'N/A' literal?

Intermediateโฑ 2 Minutesโญ 360 XP
๐Ÿค” THE QUESTION

How do we select the first available phone number from mobile, home phone, or a fallback 'N/A' literal?

๐Ÿ’ก WHAT IS IT?

coalesce() evaluates Column arguments from left to right and returns the first non-null value.

๐ŸŽฏ WHAT IS IT USED FOR?

Customer contact resolution, priority channel fallback, and merging multi-source address fields.

๐Ÿ’ป EXAMPLE
from pyspark.sql.functions import col, coalesce, lit

df = df.withColumn(
    "contact_phone",
    coalesce(col("mobile"), col("home_phone"), lit("N/A"))
)

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for First Non-Null Selection with coalesce().

  • โœ“ Import coalesce and lit
  • โœ“ Evaluate contact phone priority order
  • โœ“ Assign resolved phone with fallback