How to perform full outer join in PySpark Azure Databricks?

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

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

  • Syntax of join()
  • Full outer join using PySpark join() function
  • Full 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. Employee Dataset

emp_data = [
    ("emp1", "Raju", 2),
    ("emp2", "Manoj", 1),
    ("emp3", "Sugumar", 2),
    ("emp4", "Rupam", 2),
    ("emp5", "Kiran", 5),
]

emp_df = spark.createDataFrame(data = emp_data, schema = ["emp_id", "emp_name", "dept_id"])
emp_df.printSchema()
emp_df.show(truncate=False)

"""
root
 |-- emp_id: string (nullable = true)
 |-- emp_name: string (nullable = true)
 |-- dept_id: long (nullable = true)

+------+--------+-------+
|emp_id|emp_name|dept_id|
+------+--------+-------+
|emp1  |Raju    |2      |
|emp2  |Manoj   |1      |
|emp3  |Sugumar |2      |
|emp4  |Rupam   |2      |
|emp5  |Kiran   |5      |
+------+--------+-------+
"""
# 2. Department Dataset

dept_data = [
    (1, "IT"),
    (2, "HR"),
    (3, "Sales"),
    (4, "Marketing")
]

dept_df = spark.createDataFrame(data = dept_data, schema = ["dept_id", "dept_name"])
dept_df.printSchema()
dept_df.show(truncate=False)

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

+-------+---------+
|dept_id|dept_name|
+-------+---------+
|1      |IT       |
|2      |HR       |
|3      |Sales    |
|4      |Marketing|
+-------+---------+
"""

b) Creating a DataFrame by reading files

Download and use the below source file.

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

emp_df_2 = spark.read.format("csv").option("header", True).load(employee_file_path)
emp_df_2.printSchema()

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

"""
root
 |-- emp_id: string (nullable = true)
 |-- emp_name: string (nullable = true)
 |-- dept_id: long (nullable = true)

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

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

How to perform full outer join in PySpark Azure Databricks using the join() function?

In this section, let’s try to perform a full outer join using employee and department datasets using the join() function using various methods.

Example 1:

# Method 1:

emp_df.join(dept_df, emp_df.dept_id == dept_df.dept_id, "outer").show()

"""
Output:

+------+--------+-------+-------+---------+
|emp_id|emp_name|dept_id|dept_id|dept_name|
+------+--------+-------+-------+---------+
|  emp2|   Manoj|      1|      1|       IT|
|  emp1|    Raju|      2|      2|       HR|
|  emp3| Sugumar|      2|      2|       HR|
|  emp4|   Rupam|      2|      2|       HR|
|  null|    null|   null|      3|    Sales|
|  null|    null|   null|      4|Marketing|
|  emp5|   Kiran|      5|   null|     null|
+------+--------+-------+-------+---------+
"""

Example 2:

# Method 2:

emp_df.join(dept_df, "dept_id", "outer").show()

"""
Output:

+-------+------+--------+---------+
|dept_id|emp_id|emp_name|dept_name|
+-------+------+--------+---------+
|1      |emp2  |Manoj   |IT       |
|2      |emp1  |Raju    |HR       |
|2      |emp3  |Sugumar |HR       |
|2      |emp4  |Rupam   |HR       |
|3      |null  |null    |Sales    |
|4      |null  |null    |Marketing|
|5      |emp5  |Kiran   |null     |
+-------+------+--------+---------+
"""

In the above example, we haven’t specified the joining columns in a comparison format, instead specified the joining column name. This method returns only one joining column. This is very similar to SQL ‘USING’ clause.

How to perform full outer join in PySpark Azure Databricks using SQL expression?

In this section, let’s try to perform a full outer join using employee and department datasets using SQL expressions. In order to use a raw SQL expression, we have to convert our DataFrame into a SQL view.

Example:

emp_df.createOrReplaceTempView("employee")
dept_df.createOrReplaceTempView("department")

spark.sql('''
    SELECT *
    FROM employee AS emp
    FULL OUTER JOIN department AS dept
    ON emp.dept_id = dept.dept_id
''').show()

"""
Output:

+------+--------+-------+-------+---------+
|emp_id|emp_name|dept_id|dept_id|dept_name|
+------+--------+-------+-------+---------+
|  emp2|   Manoj|      1|      1|       IT|
|  emp1|    Raju|      2|      2|       HR|
|  emp3| Sugumar|      2|      2|       HR|
|  emp4|   Rupam|      2|      2|       HR|
|  null|    null|   null|      3|    Sales|
|  null|    null|   null|      4|Marketing|
|  emp5|   Kiran|      5|   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 full outer join in PySpark using Azure Databricks?

This could be the possible reason:

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

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

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

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