CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 3 · Lesson 16/32

    Joining and unioning Spark DataFrames

    Combine DataFrames with operations such as Inner join, left join, broadcast join, multiple keys, cross join, union, and union all.

    18 min read
    3% of exam
    9 sources
    Published 21 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Predict which rows an inner, left or cross join keeps, including rows with null or unmatched keys
    • Join on one or several keys without duplicate key columns by passing column names to on
    • Force a broadcast join with broadcast() on the small DataFrame and explain when Spark broadcasts on its own
    • Choose between union and unionByName, and remove duplicates when set semantics are needed

    Key concept

    Join contract: on + how — DataFrame.join(other, on, how) combines two DataFrames side by side. on says which rows match: column names or a Column expression. how says what happens to rows with no match: they are dropped (inner), kept with NULLs (left), or every row is paired with every other row (cross).

    1.Inner join: only rows that match on both sides

    A join puts two DataFrames side by side. A union stacks one on top of the other. Most pipelines need both. Joins enrich facts with lookups, such as orders with customers or transactions with country codes. Unions merge batches that share a shape. All the join types use the same call, df.join(other, on, how). other is the right side. on names the matching column(s) or gives a join expression. how defaults to inner.

    An inner join keeps a row only if its key finds a partner on the other side. Unmatched rows are dropped from both sides, so the result never contains a NULL-padded row. Picture an employees table where one person's dept_id is null, joined to a departments table that has a department nobody works in. The null key equals no department key, so that employee disappears. The empty department also disappears, because no employee points to it. If two of three employees match, the result has two rows. It never has three, and it never has a row with a NULL dept_name.

    Passing the key as a string, on="dept_id", also changes the output shape. The column must exist in both DataFrames, and Spark performs an equi-join that keeps one copy of the key. In the example below, name is in both inputs but appears once in the result. Only Bob is in both inputs, so only Bob comes out. Alice and Tom each lack a partner.

    Inner join on a column name: one name column, unmatched rows on both sides droppedpython
    df.join(df2, "name").show()
    # +----+---+------+
    # |name|age|height|
    # +----+---+------+
    # | Bob|  5|    85|
    # +----+---+------+

    Checkpoint 1 of 9· Fill the gap

    This inner join returns one name column and only the row whose key appears in both DataFrames. Which on argument completes it?

    df = spark.createDataFrame([Row(name="Alice", age=2), Row(name="Bob", age=5)])
    df2 = spark.createDataFrame([Row(name="Tom", height=80), Row(name="Bob", height=85)])
    
    df.join(df2,  ? ).show()
    # +----+---+------+
    # |name|age|height|
    # +----+---+------+
    # | Bob|  5|    85|
    # +----+---+------+

    Checkpoint 2 of 9· Exam question

    employees = spark.createDataFrame( [(1, "Ana", 10), (2, "Ben", 20), (3, "Cara", None)], ["emp_id", "name", "dept_id"] ) departments = spark.createDataFrame( [(10, "Sales"), (20, "Engineering"), (30, "Marketing")], ["dept_id", "dept_name"] ) result = employees.join(departments, on="dept_id", how="inner") How many rows does result contain, and why?

    Sources12

    2.Left join: keep every row from the left

    A left join keeps every row of the left DataFrame and fills the right side's columns with NULL where no match exists. Choose it when the left table is the thing you are reporting on. A list of all employees with their department name, where some names are unknown, is a left join. An inner join would quietly drop those employees, and a headcount built from it would be too low. Rows that exist only on the right still do not appear. Keeping those as well takes a full outer join. In PySpark, how="left", "leftouter" and "left_outer" all mean the same thing.

    Left join: Chloe, Evan and Amy survive with NULL deptnamesql
    > SELECT id, name, employee.deptno, deptname
       FROM employee
       LEFT JOIN department ON employee.deptno = department.deptno;
     105 Chloe      5        NULL
     103  Paul      3 Engineering
     101  John      1   Marketing
     102  Lisa      2       Sales
     104  Evan      4        NULL
     106   Amy      6        NULL
    What each join type keeps
    howMatched rowsUnmatched left rowsUnmatched right rows
    inner (default)KeptDroppedDropped
    left / leftouter / left_outerKeptKept, right columns NULLDropped
    right / rightouter / right_outerKeptDroppedKept, left columns NULL
    outer / full / fullouter / full_outerKeptKept, right columns NULLKept, left columns NULL

    Checkpoint 3 of 9· Check yourself

    A report must list every employee exactly once with their department name. Employees whose deptno is missing from the departments lookup should still appear, and departments with no employees should not. Which call produces this?

    Sources21

    3.Joining on multiple keys without duplicate columns

    Some rows are only unique on a combination of columns, such as (store_id, sku) or (region, date). For these, pass a list of column names: on=["a", "b"]. Each name must exist on both sides, and a row matches only if every listed column is equal. The output has one copy of each key column, followed by the remaining left columns and then the remaining right columns. The SQL form USING (a, b) behaves the same way.

    USING on two keys: one copy of a and b, then the other columns from each sidesql
    SELECT * FROM first JOIN second USING (a, b)
    
    is equivalent to
    
    SELECT first.a, first.b,
           first.* EXCEPT(a, b),
           second.* EXCEPT(a, b)
      FROM first JOIN second ON first.a = second.a AND first.b = second.b

    A join expression, meaning a Column such as df.name == df2.name (or several conditions combined with &), keeps both copies of the key. In the outer join below, the result has two name columns. A later select("name") on that result is ambiguous. Use the expression form when the key columns have different names, or when the condition is not plain equality. Otherwise the list of names gives a cleaner result.

    Join expression: both name columns survive, and the outer join null-pads both sidespython
    joined = df.join(df2, df.name == df2.name, "outer").sort(sf.desc(df.name))
    joined.show()
    # +-----+----+----+------+
    # | name| age|name|height|
    # +-----+----+----+------+
    # |  Bob|   5| Bob|    85|
    # |Alice|   2|NULL|  NULL|
    # | NULL|NULL| Tom|    80|
    # +-----+----+----+------+

    Checkpoint 4 of 9· Check yourself

    In orders, the customer key column is cust_id. In customers, the same key is stored in a column called id. Which join call matches each order to its customer?

    Sources21

    4.Cross join: every row with every row

    A cross join pairs every left row with every right row. Three ages crossed with two heights gives six rows. With a million rows on each side, it gives a trillion. You can request it with df.crossJoin(other) or df.join(other, how="cross"). Use it when you need every combination, such as every product against every price tier. The output grows multiplicatively, so keep cross joins out of low-latency or frequently recomputed workloads.

    crossJoin: 3 x 2 = 6 rows, with no key involvedpython
    df.crossJoin(df2.select("height")).select("age", "name", "height"
        ).orderBy("age", "name", "height").show()
    # +---+-----+------+
    # |age| name|height|
    # +---+-----+------+
    # | 14|  Tom|    80|
    # | 14|  Tom|    85|
    # | 16|  Bob|    80|
    # | 16|  Bob|    85|
    # | 23|Alice|    80|
    # | 23|Alice|    85|
    # +---+-----+------+

    An accidental cross join happens when the join condition is left out. In SQL, a JOIN with no ON or USING clause behaves as a CROSS JOIN, whatever join type you wrote. A job that ran in seconds on test data and runs for hours in production is often missing a join key.

    Checkpoint 5 of 9· Fill the gap

    No key is passed, and the result pairs each of the three people with both heights, giving six rows. Which method produces this output?

    df = spark.createDataFrame(
        [(14, "Tom"), (23, "Alice"), (16, "Bob")], ["age", "name"])
    df2 = spark.createDataFrame(
        [Row(height=80, name="Tom"), Row(height=85, name="Bob")])
    df. ? (df2.select("height")).select("age", "name", "height"
        ).orderBy("age", "name", "height").show()
    # +---+-----+------+
    # |age| name|height|
    # +---+-----+------+
    # | 14|  Tom|    80|
    # | 14|  Tom|    85|
    # | 16|  Bob|    80|
    # | 16|  Bob|    85|
    # | 23|Alice|    80|
    # | 23|Alice|    85|
    # +---+-----+------+

    Sources342

    5.broadcast() as a join option

    In a Broadcast hash join, Spark ships a full copy of the small side to every executor so the large side does not have to shuffle. In DataFrame code, the broadcast is not a separate method. You wrap the small DataFrame in broadcast() from pyspark.sql.functions and pass the wrapped DataFrame to join as usual. broadcast(df) marks that DataFrame as small enough to broadcast.

    Wrapping the small side with broadcast() before the joinpython
    from pyspark.sql import functions as dbf
    df = spark.createDataFrame([1, 2, 3, 3, 4], "int")
    df_small = spark.range(3)
    df_b = dbf.broadcast(df_small)
    df.join(df_b, df.value == df_small.id).show()

    Without any hint, Spark broadcasts automatically based on size. It estimates the size of each side in bytes and compares it with spark.sql.autoBroadcastJoinThreshold, which defaults to 10485760 bytes (10 MB). The decision depends on byte size from statistics. Row counts, the order of the DataFrames in the call, and whether broadcast was imported do not affect it, and neither does spark.sql.shuffle.partitions. Setting the threshold to -1 turns automatic broadcasting off completely.

    The hint still works when the threshold is off. The DataFrame you wrap becomes the build side, meaning the side Spark broadcasts to every executor, and Spark prioritizes broadcasting it even if its estimated size is above the threshold. Suppose a cluster has the threshold set to -1 and you join a 500 GB transactions table to a 2 MB country_codes lookup. Writing transactions.join(broadcast(country_codes), on="country_id") restores the broadcast for that one join. Wrapping transactions instead would try to ship 500 GB to every executor. There is no country_codes.broadcast() method, because broadcast is a function, not a DataFrame method. repartition(1) changes partitioning and does not broadcast anything. The join algorithm that runs after the broadcast depends on the join condition. When the join has an equi-join key, meaning an equality condition on key columns, Spark runs a broadcast hash join. When it has no equi-join key, as in a cross join, Spark runs a broadcast nested loop join instead. The broadcast() hint is written the same way in both cases.

    Checkpoint 6 of 9· Fill the gap

    Here df is the larger side of the join and df_small is a three-row lookup. The goal is to copy the lookup to every executor so the larger side does not have to shuffle. Which DataFrame should be passed to dbf.broadcast?

    from pyspark.sql import functions as dbf
    df = spark.createDataFrame([1, 2, 3, 3, 4], "int")
    df_small = spark.range(3)
    df_b = dbf.broadcast( ? )
    df.join(df_b, df.value == df_small.id).show()

    Checkpoint 7 of 9· Exam question

    A developer runs df_small.join(df_large, "key") without any join hints, and Spark's optimizer automatically converts it into a broadcast hash join. Under the default configuration, what determines whether Spark performs this automatic conversion?

    Checkpoint 8 of 9· Exam question

    A pipeline joins a 500 GB transactions DataFrame with a 2 MB country_codes lookup DataFrame. spark.sql.autoBroadcastJoinThreshold has been set to -1 in the cluster's Spark config, disabling automatic broadcast selection, but the developer still wants this specific join to avoid a shuffle. Which line correctly forces country_codes to be broadcast? from pyspark.sql.functions import broadcast result = transactions.join( ____________, on="country_id", how="inner" )

    Sources567

    6.union, UNION ALL and unionByName

    union stacks the rows of two DataFrames and keeps every row, including duplicates. That is the behaviour SQL calls UNION ALL. It does not deduplicate. If a row appears in both inputs, it appears twice in the output. To get set semantics, follow union with distinct().

    union keeps the duplicate (3, 'C'), and distinct() removes itpython
    df1 = spark.createDataFrame([(1, 'A'), (2, 'B'), (3, 'C')], ['id', 'value'])
    df2 = spark.createDataFrame([(3, 'C'), (4, 'D')], ['id', 'value'])
    df3 = df1.union(df2).distinct().sort("id")
    df3.show()
    # +---+-----+
    # | id|value|
    # +---+-----+
    # |  1|    A|
    # |  2|    B|
    # |  3|    C|
    # |  4|    D|
    # +---+-----+

    union matches columns by position, and the column names of the second DataFrame are ignored. This causes a common silent bug. Two daily extracts have the same columns in different orders, and union puts one file's values under the other file's column names. When the types happen to be compatible, nothing fails and the data is simply wrong. unionByName matches columns by name. With allowMissingColumns=True, it also accepts inputs whose column sets differ and fills the missing columns with null.

    unionByName realigns reordered columns; allowMissingColumns null-fills absent onespython
    df1 = spark.createDataFrame([[1, 2, 3]], ["col0", "col1", "col2"])
    df2 = spark.createDataFrame([[4, 5, 6]], ["col1", "col2", "col3"])
    df1.unionByName(df2, allowMissingColumns=True).show()
    # +----+----+----+----+
    # |col0|col1|col2|col3|
    # +----+----+----+----+
    # |   1|   2|   3|NULL|
    # |NULL|   4|   5|   6|
    # +----+----+----+----+
    Choosing a row-stacking method
    MethodColumns matched byDifferent column setsDuplicates
    union(other)PositionNot handledKept (UNION ALL behaviour)
    unionByName(other)NameNot allowed (allowMissingColumns defaults to False)Kept
    unionByName(other, allowMissingColumns=True)NameMissing columns filled with nullKept
    union(other).distinct()PositionNot handledRemoved

    Checkpoint 9 of 9· Match them up

    Match each row-stacking call to how it lines up columns and what it does with duplicate rows.

    Tap a term, then the definition that fits it.

    Sources89

    Sources

    (9)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “the column(s) must exist on both sides, and this performs an equi-join”
      ↩︎ Inner join: only rows that match on both sides
      “default inner. Must be one of: inner, cross, outer, full, fullouter, full_outer, left, leftouter, left_outer,”
      ↩︎ Left join: keep every row from the left
      “a string for the join column name, a list of column names, a join expression (Column), or a list of Columns.”
      ↩︎ Joining on multiple keys without duplicate columns
      “the column(s) must exist on both sides, and this performs an equi-join”
      ↩︎ Key concept
      “the column(s) must exist on both sides, and this performs an equi-join”
      ↩︎ Checkpoint
    2. 2.
      “Returns the rows that have matching values in both table references.”
      ↩︎ Inner join: only rows that match on both sides
      “appends NULL if there is no match. It is also referred to as a left outer join.”
      ↩︎ Left join: keep every row from the left
      “SELECT * will only show one occurrence for each of the columns used to match first”
      ↩︎ Joining on multiple keys without duplicate columns
      “If you omit the join_criteria the semantic of any join_type becomes that of a CROSS JOIN.”
      ↩︎ Cross join: every row with every row
      “Returns the rows that have matching values in both table references.”
      ↩︎ Exam trap 1
      “SELECT * will only show one occurrence for each of the columns used to match first”
      ↩︎ Exam trap 4
      “Returns all values from the left table reference and the matched values from the right table reference, or appends NULL if there is no match.”
      ↩︎ Checkpoint
    3. 5.
      “Marks a DataFrame as small enough for use in broadcast joins.”
      ↩︎ broadcast() as a join option
    4. 6.
      “Configures the maximum size in bytes for a table that will be broadcast to all worker nodes when performing a join.”
      ↩︎ broadcast() as a join option
      “By setting this value to -1, broadcasting can be disabled.”
      ↩︎ broadcast() as a join option
      “broadcast join (either broadcast hash join or broadcast nested loop join depending on whether there is any equi-join key)”
      ↩︎ broadcast() as a join option
      “Configures the maximum size in bytes for a table that will be broadcast to all worker nodes when performing a join.”
      ↩︎ Exam trap 2
    5. 7.
      “The join side with the hint is broadcast regardless of autoBroadcastJoinThreshold.”
      ↩︎ broadcast() as a join option
    6. 8.
      “with no automatic deduplication of elements.”
      ↩︎ union, UNION ALL and unionByName
      “resolves columns by position (not by name), following the standard behavior in SQL.”
      ↩︎ union, UNION ALL and unionByName
      “with no automatic deduplication of elements.”
      ↩︎ Exam trap 3
      “The method resolves columns by position (not by name), following the standard behavior in SQL.”
      ↩︎ Checkpoint
    7. 9.
      “resolving columns by name (rather than position). When allowMissingColumns is True, missing columns will be filled with null.”
      ↩︎ union, UNION ALL and unionByName

    Ready to test yourself?

    Practise Databricks Certified Associate Developer for Apache Spark in quiz mode.

    Spotted a mistake, or was something unclear? Tell us.