CertSafari
    Databricks Certified Data Engineer Associate· Lessons

    Domain 3 · Lesson 11/33

    Joining and unioning DataFrames in Databricks

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

    19 min read
    3.14% of exam
    11 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Choose between inner, left, right, full, semi, anti and cross joins based on which unmatched rows must survive
    • Write single-key and multi-key joins with join() and SQL USING, and predict which key columns appear in the output
    • Use broadcast() to stop Spark from shuffling the large side of a join against a small lookup table
    • Stack DataFrames with union() and unionByName(), and tell SQL UNION apart from UNION ALL

    Key concept

    Join type decides which unmatched rows survive — Every join matches rows on a key. The join type only decides what happens to rows that find no partner: inner drops them, outer joins keep them and fill the missing side with NULL, and semi or anti joins use the match as a filter.

    1.Join types and what happens to unmatched rows

    Joining puts columns from two DataFrames side by side wherever their keys match. Building a silver orders table that carries customer names, or a fact table that carries store regions, is a join. In PySpark the call is df.join(other, on, how). other is the right side, on says how rows match, and how names the join type. If you leave how out, you get an inner join.

    The join type matters for rows whose key has no partner on the other side. An inner join returns only the rows whose key exists on both sides, so an order with an unknown customer_id disappears. A left join keeps every row of the left DataFrame and fills the right-hand columns with NULL when nothing matches. A right join does the same with the sides swapped, and a full outer join keeps unmatched rows from both sides.

    Semi and anti joins filter rows instead of combining them. A left semi join returns left rows that have a match, but only the left columns: no right-hand values are added and unmatched rows are dropped. A left anti join returns the opposite set, the left rows with no match. Anti is the natural way to find, for example, transactions whose store_id is missing from stores. A cross join ignores keys entirely and pairs every left row with every right row.

    A left join keeps all six employees; departments 4, 5 and 6 do not exist, so deptname is NULL for themsql
    > 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
    Six employees joined to three departments (deptno 1–3): what each join type returns
    Join type (how=)Rows returnedUnmatched employees (deptno 4, 5, 6)Columns
    inner3DroppedBoth sides
    left6Kept, deptname NULLBoth sides
    right3Dropped (every department has a match)Both sides
    full6Kept, deptname NULLBoth sides
    left_semi3DroppedLeft side only
    left_anti3Only these are returnedLeft side only

    Checkpoint 1 of 9· Fill the gap

    This query returned all six employees, with NULL in deptname for departments 4, 5 and 6, which do not exist. Which join type fills the blank?

    > SELECT id, name, employee.deptno, deptname
       FROM employee
        ?  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

    Checkpoint 2 of 9· Match them up

    You join transactions (left) to stores (right) on store_id. Match each join type to the result it gives.

    Tap a term, then the definition that fits it.

    Checkpoint 3 of 9· Exam question

    A data engineer has a orders DataFrame and a customers DataFrame and wants to keep only the rows where the customer_id value exists in both DataFrames. Which join type produces this result?

    Checkpoint 4 of 9· Exam question

    A pipeline joins a transactions DataFrame to a stores DataFrame so that every transaction is retained in the output even when the corresponding store_id is missing from stores. Which join accomplishes this while preserving all transaction rows?

    Sources12

    2.Join keys: column names, expressions and multiple keys

    The on argument takes four shapes: a column name, a list of column names, a Column expression, or a list of Columns. The choice affects the output schema. If you pass a name or a list of names, that column must exist on both sides and Spark runs an equi-join. The output then has the key only once. If you pass an expression such as df.name == df2.name, both key columns stay in the result, so a later select("name") is ambiguous.

    Joining on the string "name" yields one name column; joining on an expression keeps bothpython
    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, "name").show()
    # +----+---+------+
    # |name|age|height|
    # +----+---+------+
    # | Bob|  5|    85|
    # +----+---+------+
    
    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|
    # +-----+----+----+------+

    Use a multi-key join when one column does not identify a row, for example sales keyed by both store_id and sale_date. In PySpark, pass a list such as on=["store_id", "sale_date"]. In SQL, USING (a, b) does the same thing. SELECT * FROM first JOIN second USING (a, b) is equivalent to an ON first.a = second.a AND first.b = second.b join, and it shows each key column once, before the remaining left and right columns. A key named in USING that is missing from one side raises UNRESOLVED_USING_COLUMN_FOR_JOIN.

    A self-join needs aliases because both sides have identical column names. df.alias("a").join(df.alias("b"), sf.col("a.name") == sf.col("b.name"), "outer") lets you refer to either side's column without ambiguity.

    Checkpoint 5 of 9· Check yourself

    You need to combine daily_sales with daily_targets. A row is identified by store_id and sale_date together. Only matched rows should be kept, the target columns must be included, and SELECT * should show store_id and sale_date once each. Which FROM clause does this?

    Sources21

    3.Cross joins and the Cartesian product

    A cross join pairs every row on the left with every row on the right, so the output row count is the product of the two input counts. It is the right tool when you need every combination, such as every store against every day of a calendar to build a grid you can fill in later. In PySpark it is df.crossJoin(other) or join(other, how="cross"), and in SQL it is CROSS JOIN.

    crossJoin pairs each of three people with each of two heights, giving six rowspython
    from pyspark.sql import Row
    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.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|
    # +---+-----+------+

    You can also get a cross join by accident. In SQL, if you write a join without an ON or USING clause, any join type behaves like a CROSS JOIN. A forgotten condition between a million-row table and a thousand-row table produces a billion rows. That is why Databricks calls cross joins expensive and advises removing them from queries that need low latency or frequent recomputation. A cross join never speeds up an ordinary keyed join: it does more work, not less.

    Join order is the other cost lever when a query chains several joins. Join the smallest tables first, then join that result to the larger ones.

    Checkpoint 6 of 9· Check yourself

    A nightly job runs SELECT * FROM orders LEFT JOIN regions. orders has 1,000,000 rows and regions has 1,000 rows. The author forgot the ON clause. What does Databricks SQL return?

    Sources34

    4.Broadcast joins for a large table and a small one

    In a standard distributed join, both DataFrames are shuffled across the cluster so that rows with the same key end up on the same machine. When one side is 500 GB of events and the other is a 40 MB lookup table, almost all of that network traffic comes from moving the large side. A broadcast join avoids this: Spark sends a full copy of the small table to every worker node. Each partition of the large table is then joined where it already sits, and the large side is not shuffled.

    broadcast() from pyspark.sql.functions marks a DataFrame as small enough for a broadcast join. You wrap the small side, not the large one, and pass it to an ordinary join. The SQL equivalent is the /*+ BROADCAST(t1) */ hint, with BROADCASTJOIN and MAPJOIN as aliases.

    Wrapping the small DataFrame with broadcast() before joiningpython
    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()

    Spark also broadcasts automatically when a table is under spark.sql.autoBroadcastJoinThreshold, which defaults to 10 MB in Apache Spark. At 40 MB the lookup table is over that limit, so without a hint the join can fall back to shuffling both sides. An explicit hint removes the guesswork, because the side with the hint is broadcast regardless of the threshold. Changing the threshold itself, and the runtime re-planning that can switch join strategies, belong to Spark tuning parameters.

    Checkpoint 7 of 9· Fill the gap

    In this sample, df is the side that should stay where it is and df_small is the lookup table. Which DataFrame belongs in the blank so that Spark copies only the small table to every worker and does not shuffle the large one?

    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 8 of 9· Exam question

    A join between a 500 GB events DataFrame and a 40 MB lookup_codes DataFrame is running slowly because Spark shuffles both sides across the cluster. Which change is most likely to speed up this join?

    Sources5678

    5.Stacking rows: union, unionByName, UNION and UNION ALL

    A union adds one DataFrame's rows below another's, where a join adds columns side by side. You union when monthly extracts, regional feeds or a backfill share a schema and need to become one table. In PySpark, union() lines up columns by position: the first column of other goes under the first column of self, whatever the names are. It also does not remove duplicates, so it keeps every row, like SQL UNION ALL. If you need distinct rows, follow it with distinct(); general row deduplication is covered in deduplication operations.

    unionByName matches columns by name, so df2's values are reordered to fit df1's columnspython
    df1 = spark.createDataFrame([[1, 2, 3]], ["col0", "col1", "col2"])
    df2 = spark.createDataFrame([[4, 5, 6]], ["col1", "col2", "col0"])
    df1.unionByName(df2).show()
    # +----+----+----+
    # |col0|col1|col2|
    # +----+----+----+
    # |   1|   2|   3|
    # |   6|   4|   5|
    # +----+----+----+

    Positional matching fails silently, so it is the riskier choice. If one source writes (id, amount, fee) and another writes (id, fee, amount), union() still succeeds and puts fees in the amount column as long as the types are compatible. unionByName() avoids this. With allowMissingColumns=True it can also stack inputs whose column sets differ, such as a feed that added a column last quarter. Columns missing from one input are filled with NULL, and the result contains every column from both.

    SQL works the other way round from the DataFrame API. A plain UNION means UNION DISTINCT and removes duplicate rows. UNION ALL keeps them. Both sides must have the same number of columns, or Databricks raises NUM_COLUMNS_MISMATCH. Each result column takes the least common type of the two inputs.

    number1 holds 3, 1, 2, 2, 3, 4 and number2 holds 5, 1, 1, 2: how each operation treats duplicates
    OperationMatches columns byDuplicatesRows from the example
    SQL UNION (same as UNION DISTINCT)PositionRemoved5 (1, 3, 5, 4, 2)
    SQL UNION ALLPositionKept10
    DataFrame union()PositionKept10
    DataFrame unionByName()NameKept10

    Checkpoint 9 of 9· Fill the gap

    df1 and df2 both contain the row (3, 'C'). The combined output below should list that row only once. Which method belongs in the blank?

    df1 = spark.createDataFrame([(1, 'A'), (2, 'B'), (3, 'C')], ['id', 'value'])
    df2 = spark.createDataFrame([(3, 'C'), (4, 'D')], ['id', 'value'])
    df3 = df1.union(df2). ? ().sort("id")
    df3.show()
    # +---+-----+
    # | id|value|
    # +---+-----+
    # |  1|    A|
    # |  2|    B|
    # |  3|    C|
    # |  4|    D|
    # +---+-----+

    Sources91011

    Practise it for real

    In a notebook, compare union(), union().distinct() and unionByName(allowMissingColumns=True) on small DataFrames.

    1. 1.Create df1 = spark.createDataFrame([(1, 'A'), (2, 'B'), (3, 'C')], ['id', 'value']) and df2 = spark.createDataFrame([(3, 'C'), (4, 'D')], ['id', 'value']), then run df1.union(df2).show().

      Why: This shows that union() keeps every row from both inputs.

      You should see: Five rows, with (3, C) appearing twice.

    2. 2.Run df1.union(df2).distinct().sort("id").show().

      Why: union() never deduplicates, so removing duplicates needs an explicit distinct().

      You should see: Four rows: ids 1, 2, 3 and 4, each once.

    3. 3.Create df1 = spark.createDataFrame([[1, 2, 3]], ["col0", "col1", "col2"]) and df2 = spark.createDataFrame([[4, 5, 6]], ["col1", "col2", "col3"]), then run df1.unionByName(df2, allowMissingColumns=True).show().

      Why: This shows name-based matching across inputs whose column sets differ.

      You should see: Four columns, col0 to col3. The first row has NULL in col3 and the second row has NULL in col0.

    Stuck? Get a nudge

    Run step 3 again without allowMissingColumns=True and compare the result with the default behaviour.

    Sources

    (11)

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

    1. 1.
      “Returns the rows that have matching values in both table references.”
      ↩︎ Join types and what happens to unmatched rows
      “appends NULL if there is no match”
      ↩︎ Join types and what happens to unmatched rows
      “Returns the values from the left table reference that have no match with the right table reference.”
      ↩︎ Join types and what happens to unmatched rows
      “SELECT * will only show one occurrence for each of the columns used to match first”
      ↩︎ Join keys: column names, expressions and multiple keys
      “If a column is not found in one of the relations, Databricks raises UNRESOLVED_USING_COLUMN_FOR_JOIN.”
      ↩︎ Join keys: column names, expressions and multiple keys
      “Returns all values from both relations, appending NULL values on the side that does not have a match.”
      ↩︎ Key concept
      “Returns values from the left side of the table reference that has a match with the right.”
      ↩︎ Exam trap 1
      “If you omit the join_criteria the semantic of any join_type becomes that of a CROSS JOIN.”
      ↩︎ Exam trap 2
      “[ LEFT ] ANTI Returns the values from the left table reference that have no match with the right table reference.”
      ↩︎ Checkpoint
      “When you specify USING or NATURAL, SELECT * will only show one occurrence for each of the columns used to match first”
      ↩︎ Checkpoint
      “Returns the Cartesian product of two relations.”
      ↩︎ Prediction
      “If you omit the join_criteria the semantic of any join_type becomes that of a CROSS JOIN.”
      ↩︎ Checkpoint
    2. 4.
      “Cross joins are expensive. Remove cross joins from workloads and queries that require low latency or frequent recomputation.”
      ↩︎ Cross joins and the Cartesian product
      “When performing multiple joins, always join your smallest tables first and then join the result with larger tables.”
      ↩︎ Cross joins and the Cartesian product
    3. 6.
      “It chose a broadcast join instead of shuffling data across the cluster”
      ↩︎ Broadcast joins for a large table and a small one
    4. 7.
      “Configures the maximum size in bytes for a table that will be broadcast to all worker nodes when performing a join.”
      ↩︎ Broadcast joins for a large table and a small one
      “spark.sql.autoBroadcastJoinThreshold | 10485760 (10 MB)”
      ↩︎ Broadcast joins for a large table and a small one
    5. 8.
      “BROADCASTJOIN and MAPJOIN are supported as aliases for BROADCAST.”
      ↩︎ Broadcast joins for a large table and a small one
      “The join side with the hint is broadcast regardless of autoBroadcastJoinThreshold.”
      ↩︎ Exam trap 3
    6. 9.
      “This method performs a SQL-style set union of the rows from both DataFrame objects, with no automatic deduplication of elements.”
      ↩︎ Stacking rows: union, unionByName, UNION and UNION ALL
      “The method resolves columns by position (not by name), following the standard behavior in SQL.”
      ↩︎ Exam trap 4
    7. 10.
      “When allowMissingColumns is True, missing columns will be filled with null.”
      ↩︎ Stacking rows: union, unionByName, UNION and UNION ALL
      “resolving columns by name (rather than position)”
      ↩︎ Prediction
    8. 11.
      “If DISTINCT is specified the result does not contain any duplicate rows. This is the default.”
      ↩︎ Stacking rows: union, unionByName, UNION and UNION ALL
      “If the number of columns differs, Databricks raises NUM_COLUMNS_MISMATCH.”
      ↩︎ Stacking rows: union, unionByName, UNION and UNION ALL
      “The type of each result column is the least common type of the respective columns in subquery1 and subquery2.”
      ↩︎ Stacking rows: union, unionByName, UNION and UNION ALL

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