How to perform Left Outer Join in PySpark Azure Databricks?

Are you looking to find out how to perform the left outer join in PySpark on the Azure Databricks cloud or maybe you are looking for a solution, to find a method to do the left outer join in PySpark? If you are looking for any of these problem solutions, you have landed on the correct page. I will also show you how to use both PySpark and Spark SQL ways of doing the left outer join in Azure Databricks. I will explain it with a practical example. So please don’t waste time let’s start with a step-by-step guide to understand left outer join in PySpark Azure Databricks.

In this blog, I will teach you the following with practical examples:

  • Syntax of join()
  • Left Outer Join using PySpark join() function
  • Left Outer Join using SQL expression

join() method is used to join two Dataframes together based on condition specified in PySpark Azure Databricks.

Syntax: dataframe_name.join()

What is the syntax of the join() function in PySpark Azure Databricks?

The syntax is as follows:

dataframe_name.join(other, on, how)
Parameter NameRequiredDescription
other (Dataframe)YesIt represents the second column to be joined.
on (str, list, or Column)YesA string for the join column name, a list of column names, a join expression (Column), or a list of Columns. If on is a string or a list of strings indicating the name of the join column(s), the column(s) must exist on both sides.
how (str)OptionalIt represents join type, by default how=”inner”.
Table 1: join() Method in PySpark Databricks Parameter list with Details

Apache Spark Official documentation link: join()

Create a simple DataFrame

Gentle reminder:

In Databricks,

  • sparkSession made available as spark
  • sparkContext made available as sc

In case, you want to create it manually, use the below code.

from pyspark.sql.session import SparkSession

spark = SparkSession.builder 
    .master("local[*]") 
    .appName("azurelib.com") 
    .getOrCreate()

sc = spark.sparkContext

a) Create manual PySpark DataFrame

# 1. Student Dataset
student_data = [
    (1,"Clara",2),
    (2,"Conny",3),
    (3,"Sallie",1),
    (4,"Magdalene",3),
    (5,"Palm",3)
]

std_df = spark.createDataFrame(student_data, schema=["id","name","dept_id"])
std_df.printSchema()
std_df.show(truncate=False)

"""
root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- dept_id: long (nullable = true)

+---+---------+-------+
|id |name     |dept_id|
+---+---------+-------+
|1  |Clara    |2      |
|2  |Conny    |3      |
|3  |Sallie   |1      |
|4  |Magdalene|3      |
|5  |Palm     |3      |
+---+---------+-------+
"""
# 2. Department Dataset

dept_data = [
    (1,"civil"),
    (2,"mechanical"),
    (5,"ece")
]

dept_df = spark.createDataFrame(dept_data, schema=["id","name"])
dept_df.printSchema()
dept_df.show(truncate=False)

"""
root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)

+---+----------+
|id |name      |
+---+----------+
|1  |civil     |
|2  |mechanical|
|5  |ece       |
+---+----------+
"""

b) Creating a DataFrame by reading files

Download and use the below source file.

# replace the file_path with the source file location which you have downloaded.

std_df_2 = spark.read.format("csv").option("header", True).load(student_file_path)
std_df_2.printSchema()

dept_df_2 = spark.read.format("csv").option("header", True).load(department_file_path)
dept_df_2.printSchema()

"""
root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- dept_id: long (nullable = true)

root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
"""

Note: Here, I will be using the manually created DataFrame.

How to perform Left Outer Join in PySpark Azure Databricks using the join() function?

Before diving in, let’s have a brief discussion about what is meant by Left Outer Join. This join returns all rows from the left and right DataFrame, but the value of the left DataFrame which doesn’t have a matching value on the right DataFrame will be replaced by null. Let’s understand this with some practical examples.

Example:

# Method 1:
std_df.join(dept_df, std_df.dept_id == dept_df.id, "left").show()

# Method 2:
std_df.join(dept_df, std_df.dept_id == dept_df.id, "leftouter").show()

# Method 3:
std_df.join(dept_df, std_df.dept_id == dept_df.id, "left_outer").show()

# The above codes generates the same ouput

"""
Output:

+---+---------+-------+----+----------+
| id|     name|dept_id|  id|      name|
+---+---------+-------+----+----------+
|  3|   Sallie|      1|   1|     civil|
|  1|    Clara|      2|   2|mechanical|
|  2|    Conny|      3|null|      null|
|  4|Magdalene|      3|null|      null|
|  5|     Palm|      3|null|      null|
+---+---------+-------+----+----------+
"""

In the above example, we can see that we don’t have department 3 on the right DataFrame, hence it was replaced with null value. We can use “left”, “leftouter” and “left_outer” inside the join() function to perform left outer join.

If you don’t want duplicate columns while joining, try passing the joining column name in str or list[str] format. But this works only when you have same column name on both DataFrames. Therefore rename one of the joining column. No problem, if you don’t understand let’s do this with an example.

std_df.join(dept_df.withColumnRenamed("id", "dept_id"), "dept_id", "left").show()

"""
Output:

+-------+---+---------+----------+
|dept_id| id|     name|      name|
+-------+---+---------+----------+
|      1|  3|   Sallie|     civil|
|      2|  1|    Clara|mechanical|
|      3|  2|    Conny|      null|
|      3|  4|Magdalene|      null|
|      3|  5|     Palm|      null|
+-------+---+---------+----------+

"""

How to perform Left Outer Join in PySpark Azure Databricks using SQL expression?

In this section, let’s perform the Left Outer Join using SQL expressions. In order to use a raw SQL expression, we have to convert our DataFrame into a SQL view.

std_df.createOrReplaceTempView("student")
dept_df.createOrReplaceTempView("department")

Example:

spark.sql('''
    SELECT *
    FROM student AS std
    LEFT OUTER JOIN department AS dept
    ON std.dept_id = dept.id
''').show()

"""
Output:

+---+---------+-------+----+----------+
| id|     name|dept_id|  id|      name|
+---+---------+-------+----+----------+
|  3|   Sallie|      1|   1|     civil|
|  1|    Clara|      2|   2|mechanical|
|  2|    Conny|      3|null|      null|
|  4|Magdalene|      3|null|      null|
|  5|     Palm|      3|null|      null|
+---+---------+-------+----+----------+
"""

I have attached the complete code used in this blog in notebook format to this GitHub link. You can download and import this notebook in databricks, jupyter notebook, etc.

When should you use left outer join in PySpark using Azure Databricks?

This could be the possible reason:

To extract all the Left DataFrame that satisfies the joining column condition or not and Right DataFrame records.

Real World Use Case Scenarios for using left outer join in PySpark Azure Databricks?

Assume that you have a student and department data set. The student dataset has the student id, name, and department id. And the department dataset has the department id and name of that department. You want to fetch all the students and their corresponding department records. The left outer join combines the left DataFrame record with the matching right DataFrame records, and the non-matching right DataFrame records will be replaced with null values.

What are the alternatives for performing left outer join in PySpark using Azure Databricks?

There are multiple alternatives for the left outer join in PySpark DataFrame, which are as follows:

  • DataFrame.join(): used for combining DataFrames
  • Using PySpark SQL expressions

Final Thoughts

In this article, we have learned about how to perform left outer join in PySpark Azure Databricks along with the examples explained clearly. I have also covered different scenarios with practical examples that could be possible. I hope the information that was provided helped in gaining knowledge.

Please share your comments and suggestions in the comment section below and I will try to answer all your queries as time permits.

Arud Seka Berne S

As a big data engineer, I design and build scalable data processing systems and integrate them with various data sources and databases. I have a strong background in Python and am proficient in big data technologies such as Hadoop, Hive, Spark, Databricks, and Azure. My interest lies in working with large datasets and deriving actionable insights to support informed business decisions.