How to perform Right Outer Join in PySpark Azure Databricks?

Are you looking to find out how to perform the right outer join in PySpark on the Azure Databricks cloud or maybe you are looking for a solution, to find a method to do the right 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 right 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 right outer join in PySpark Azure Databricks.

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

  • Syntax of join()
  • Right Outer Join using PySpark join() function
  • Right 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"),
    (3,"cse"),
    (4,"it"),
    (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|
|3  |cse       |
|4  |it        |
|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 Right Outer Join in PySpark Azure Databricks using the join() function?

Before diving in, let’s have a brief discussion about what is meant by Right Outer Join. This join returns all rows from the left and right DataFrame, but the value of right DataFrame which doesn’t have a matching value on the left 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, "right").show()

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

# Method 3:
std_df.join(dept_df, std_df.dept_id == dept_df.id, "right_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|  3|       cse|
|   4|Magdalene|      3|  3|       cse|
|   5|     Palm|      3|  3|       cse|
|null|     null|   null|  4|        it|
|null|     null|   null|  5|       ece|
+----+---------+-------+---+----------+
"""

In the above example, we can see that we don’t have department 4 and 5 on the left DataFrame, hence it was replaced with null value.

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", "right").show()

"""
Output:

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

"""

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

In this section, let’s perform the Right 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
    RIGHT 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|  3|       cse|
|   4|Magdalene|      3|  3|       cse|
|   5|     Palm|      3|  3|       cse|
|null|     null|   null|  4|        it|
|null|     null|   null|  5|       ece|
+----+---------+-------+---+----------+
"""

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 right outer join in PySpark using Azure Databricks?

This could be the possible reason:

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

Real World Use Case Scenarios for using right 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 right outer join combines the left DataFrame record with the matching right DataFrame records, and the non-matching left DataFrame records will be replaced with null values.

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

There are multiple alternatives for the right 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 the right 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.

PySpark in Azure Databricks, as explained by Arud Seka Berne S on azurelib.com.

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.