← BuildandTeach Tech Tutorials posts

Published · By Henry Palma

Databricks Data Engineer Associate Exam Prep, Lesson 8: Joins and Unions in PySpark (Broadcast and Cross Joins)

Databricks Data Engineer Associate exam prep: inner, left, multi-key, broadcast and cross joins in PySpark, plus union vs union all and unionByName.

Databricks Data Engineer Associate Exam Prep, Lesson 8: Joins and Unions in PySpark (Broadcast and Cross Joins)

Exam-style question: Monday's orders extract has orders 5001 and 5002. A resend file has orders 5002 and 5003, with the same columns in the same order. You run ordersmon.union(ordersresend).count(). What do you get? Four. In PySpark, union() keeps duplicate rows, the same as UNION ALL in SQL, so order 5002 appears twice. Add .distinct() if you want three. This post follows Lesson 8 of the Databricks Data Engineer Associate exam prep series, in Section 3 of the August 2026 exam guide, Data Transformation and Modeling (22% of the exam).

Watch on YouTube

Video thumbnail
Video thumbnail

The notebook and cheat sheet are in the A08 folder on GitHub. The PDF cheat sheet is in the same folder. This is independent study material, not official Databricks training.

The exam objective

Section 3 of the exam guide lists this objective: combine DataFrames with operations such as inner join, left join, broadcast join, multiple keys, cross join, union, and union all.

In practice, that comes down to three questions. Which join type keeps the rows I need? Which side, if any, should be broadcast? And does this union keep or remove duplicates?

Everything here runs in Databricks Free Edition, in a Python notebook on serverless compute with Unity Catalog. The outputs in this post were checked with a local Apache Spark 4.0 run of the same code, not on Databricks.

The retail tables

From this lesson on, the series uses one small retail dataset: customers, orders, order_items and products. All names are fictional.

customers (4 rows):

| customerid | customername | state | |---|---|---| | 101 | Ana Lopez | TX | | 102 | Ben Wu | TX | | 103 | Cara Diaz | CO | | 104 | Dev Shah | OK |

orders (4 rows). Order 5004 belongs to customer 105, who is not in customers yet:

| orderid | customerid | order_date | |---|---|---| | 5001 | 101 | 2026-11-02 | | 5002 | 102 | 2026-11-03 | | 5003 | 101 | 2026-11-04 | | 5004 | 105 | 2026-11-05 |

products (3 rows): P1 Coffee mug 12.00, P2 Notebook 4.50, P3 Desk lamp 30.00. Price is DECIMAL(10,2).

order_items (5 rows), one row per order line:

| orderid | lineno | product_id | quantity | |---|---|---|---| | 5001 | 1 | P1 | 2 | | 5001 | 2 | P2 | 1 | | 5002 | 1 | P3 | 1 | | 5003 | 1 | P2 | 3 | | 5004 | 1 | P1 | 1 |

The notebook creates these as managed tables in a new schema in the workspace catalog, the same way A07 did:

from pyspark.sql import functions as F
from pyspark.sql.functions import broadcast

customers = spark.read.table("customers") orders = spark.read.table("orders") orderitems = spark.read.table("orderitems") products = spark.read.table("products") ```

Inner join vs left join

join defaults to an inner join. An inner join keeps only rows with a match on both sides, so order 5004 disappears without any error:

orders.join(customers, "customer_id").count()           # 3
orders.join(customers, "customer_id", "left").count()   # 4

The left join keeps every order. Order 5004 comes back with NULL customer_name and state. When the left table is your fact table (orders, order lines), a left join is usually the safe default, because it never loses facts. Then count the unmatched rows on purpose:

orders.join(customers, "customer_id", "left_anti").count()   # 1 (order 5004)

A left_anti join returns the left rows that have no match. It is a quick way to find orphan keys before they become a reporting gap.

Two details the exam likes:

  • Passing the key as a string or a list of strings ("customerid") does an equi-join and keeps one customerid column. Passing an expression (orders.customerid == customers.customerid) keeps both columns, so a later select("customer_id") is ambiguous.
  • how accepts inner, left (or leftouter), right, full, cross, leftsemi and left_anti, among other spellings.

Joining on multiple keys

orderitems has a two-part key: orderid plus lineno. Suppose a returns table has one row, order 5001 line 2, reason damaged. If you join on orderid alone, both lines of order 5001 match:

order_items.join(returns, "order_id").count()                # 2 (wrong)
order_items.join(returns, ["order_id", "line_no"]).count()   # 1 (right)

Join on the full key. A list of column names joins on all of them, and the columns must exist on both sides. If the names differ, combine conditions with &, for example (a.orderid == b.ordid) & (a.line_no == b.line).

The same rule applies to dimension tables. If customers had customer 101 twice, every order for 101 would match twice. With this data, the left join would return 6 rows instead of 4. Check that the dimension key is unique before you join.

Broadcast joins: send the small table, not the big one

In a normal join between two large tables, Spark shuffles both sides across the cluster by the join key and uses a sort merge join. A broadcast join sends a full copy of the small table to every executor instead, so the large table does not have to be shuffled. This is called a broadcast hash join.

You ask for one with broadcast() on the small DataFrame:

orders.join(broadcast(customers), "customer_id", "left")

In the plan from explain(), this shows up as BroadcastHashJoin ... LeftOuter, BuildRight, which means customers (the right side) is the side that was copied.

What the docs say about choosing:

  • Spark broadcasts a table automatically when its estimated size is under spark.sql.autoBroadcastJoinThreshold (10 MB by default in Apache Spark; set it to -1 to turn automatic broadcasting off). The broadcast() hint overrides that threshold.
  • On Databricks, adaptive query execution (AQE) is on by default and can switch a sort merge join to a broadcast hash join at runtime when one side turns out to be small (spark.databricks.adaptive.autoBroadcastJoinThreshold, 30MB by default). Databricks still recommends the hint when you know the table is small, because a broadcast planned up front usually beats one AQE picks after shuffling.
  • Some join types cannot broadcast a given side. AQE cannot broadcast the left side of a LEFT OUTER JOIN. In the local check, putting the hint on orders in broadcast(orders).join(customers, "customer_id", "left") was ignored, and Spark fell back to a sort merge join. Keep the big table on the left and broadcast the small dimension on the right.
  • The hint is a suggestion. The Databricks hints reference says a hinted strategy is not guaranteed if it does not support the join type.

The trap is broadcasting the big table. Every executor has to hold a full copy of the broadcast side in memory, so a broadcast of a large fact table can be slower than a shuffle, or fail. Broadcast dimensions such as customers and products. Do not broadcast orders or order_items.

In SQL, the same hint goes in a comment after SELECT:

SELECT /*+ BROADCAST(c) */ o.order_id, c.customer_name
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.customer_id;

BROADCASTJOIN and MAPJOIN are accepted aliases.

Cross joins multiply rows

A cross join pairs every row on the left with every row on the right, with no join key. The row count is the product of the two inputs:

customers.crossJoin(products).count()   # 12 = 4 x 3

Twelve rows is fine. The same pattern on 1,000,000 customers and 10,000 products produces 10,000,000,000 rows. That is the trap: a cross join, or a join whose condition matches far more rows than you expected, can explode the row count. Use crossJoin only when you really want every combination, such as building a calendar-by-store grid, and check the counts of both inputs first.

Union vs union all

Here is where PySpark and SQL use the same word differently.

| You write | Duplicates | Columns matched by | |---|---|---| | SQL UNION (same as UNION DISTINCT) | removed | position | | SQL UNION ALL | kept | position | | PySpark df1.union(df2) | kept | position | | PySpark df1.unionAll(df2) (alias of union) | kept | position | | PySpark df1.unionByName(df2) | kept | name |

With the two extracts from the opening question:

orders_mon.union(orders_resend).count()              # 4
orders_mon.union(orders_resend).distinct().count()   # 3
SELECT * FROM orders_mon UNION     SELECT * FROM orders_resend;   -- 3 rows
SELECT * FROM orders_mon UNION ALL SELECT * FROM orders_resend;   -- 4 rows

The PySpark docs say union does no automatic deduplication and resolves columns by position, like standard SQL. unionAll is an alias for union. To get SQL UNION behavior from a DataFrame, add .distinct().

The silent column-order bug

Position matching has a second trap. A store extract arrives with the columns in a different order: customerid, orderid, orderdate. Both ID columns are integers, so union does not fail. It quietly puts customer 103 in the orderid column:

| orderid | customerid | order_date | |---|---|---| | 5001 | 101 | 2026-11-02 | | 5002 | 102 | 2026-11-03 | | 103 | 5005 | 2026-11-05 |

unionByName matches by column name and returns order 5005 for customer 103. If one side has an extra column, both union and unionByName fail with NUMCOLUMNSMISMATCH. unionByName(other, allowMissingColumns=True) fills the missing column with NULL instead.

On the job: a silver order-line table

The task: one row per order line, with the order date, the customer name and the product price, ready for reporting. order_items and orders are the large tables. customers and products are small dimensions.

order_lines = (order_items
  .join(orders, "order_id")                               # fact to fact: shuffle
  .join(broadcast(customers), "customer_id", "left")     # small dim: broadcast
  .join(broadcast(products), "product_id")               # small dim: broadcast
  .withColumn("line_total", F.col("quantity") * F.col("price"))
  .select("order_id", "line_no", "order_date", "customer_id", "customer_name",
          "product_name", "quantity", "price", "line_total"))

orderlines.write.mode("overwrite").saveAsTable("silverorder_lines") ```

Result, five rows, one per order line:

| orderid | lineno | customername | productname | quantity | price | line_total | |---|---|---|---|---|---|---| | 5001 | 1 | Ana Lopez | Coffee mug | 2 | 12.00 | 24.00 | | 5001 | 2 | Ana Lopez | Notebook | 1 | 4.50 | 4.50 | | 5002 | 1 | Ben Wu | Desk lamp | 1 | 30.00 | 30.00 | | 5003 | 1 | Ana Lopez | Notebook | 3 | 4.50 | 13.50 | | 5004 | 1 | NULL | Coffee mug | 1 | 12.00 | 12.00 |

The line totals add up to 84.00. Order 5004 stays in the table with a NULL customer name, because the customer join is a left join. With an inner join there, the silver table would have four lines and the total would drop to 72.00 with no error. In the plan, orders and order_items use a sort merge join, and both dimension joins show as BroadcastHashJoin with BuildRight.

Practical takeaway: a join-choice checklist

Before any join:

  1. Keys. Name the full key (all parts of a composite key). Check the key is unique on the dimension side. Check the data types match.
  2. Join type. Do I need every row from the fact table? Use left. Only matches? inner. Every combination on purpose? crossJoin, after checking both counts.
  3. Broadcast vs shuffle. Broadcast the small dimension on the right side. Never broadcast the large fact table. Two large tables: let Spark shuffle.
  4. Union. PySpark union keeps duplicates and matches by position. Use unionByName for files from different sources, and .distinct() only when duplicates are truly unwanted.
  5. Reconcile. Compare row counts in and out, and count unmatched keys.

A reusable orders-to-customers join that does steps 1, 3 and 5:

def join_orders_to_customers(
        orders_df, customers_df, key="customer_id"):
    dupes = (customers_df.groupBy(key).count()
             .filter("count > 1").count())
    if dupes:
        raise ValueError(
            f"customers has {dupes} duplicate "
            f"{key} value(s)")
    joined = orders_df.join(
        broadcast(customers_df), key, "left")
    unmatched = joined.filter(
        F.col("customer_name").isNull()).count()
    print(f"{orders_df.count()} orders in, "
          f"{joined.count()} out, "
          f"{unmatched} without a customer")
    return joined

joinordersto_customers(orders, customers) # 4 orders in, 4 out, 1 without a customer ```

If customers had a duplicate 101, the function stops with customers has 1 duplicate customer_id value(s) instead of writing six rows.

For a slower walk through inner vs left joins outside the exam series, see PySpark Joins and Aggregations: Inner vs Left Joins on Databricks Free Edition.

Practice exam-style question

A data engineer joins a 2-billion-row orderitems table to a 5,000-row products table on productid, keeping every order line. Which code is the best choice?

  • A) broadcast(orderitems).join(products, "productid", "left")
  • B) orderitems.join(broadcast(products), "productid", "left")
  • C) orderitems.crossJoin(products).filter(orderitems.productid == products.productid)
  • D) products.join(orderitems, "productid", "inner")

Answer: B. products is the small table, so it is the one to broadcast, and the left join keeps every order line. A broadcasts the huge table, and a left outer join cannot broadcast its left side anyway. C builds a 10-trillion-row intermediate result before filtering. D is an inner join, so lines with an unknown product would be lost.

Key takeaways

  • join defaults to inner, which silently drops unmatched rows. Use left for fact tables and count orphans with left_anti.
  • Join on the full key, and make sure the dimension key is unique, or rows multiply.
  • Broadcast the small dimension on the right side. Broadcasting a large table wastes memory, and a left join cannot broadcast its left side.
  • A cross join returns left rows times right rows. Check both counts first.
  • Memory trick: PySpark union is UNION ALL in disguise. It keeps every row and matches columns by position. Add distinct() to dedupe, and use unionByName to match by name.

Next lesson (Lesson 9): deduplication and aggregates.

Check your understanding

1. orders has 4 rows. One order's customerid is missing from customers. What does orders.join(customers, "customerid").count() return?

  • A) 4
  • B) 3
  • C) 5
  • D) An error, because one key has no match

2. df1 and df2 each have 2 rows, and one row is identical in both. What does df1.union(df2).count() return?

  • A) 2
  • B) 3
  • C) 4
  • D) An error, because of the duplicate row

3. Which DataFrame method matches columns by name instead of position?

  • A) union
  • B) unionAll
  • C) unionByName
  • D) crossJoin

4. customers has 4 rows and products has 3 rows. How many rows does customers.crossJoin(products) return?

  • A) 3
  • B) 4
  • C) 7
  • D) 12

5. You left-join a large orders table to a small customers table. Which table should get the broadcast() hint?

  • A) orders, because it is on the left
  • B) customers, because it is the small table on the right
  • C) Both tables
  • D) Neither, because broadcast joins only work for inner joins

Answer key

  1. B. The default join is inner, so the order with no matching customer is dropped without an error.
  2. C. PySpark union keeps duplicates, like SQL UNION ALL. Add .distinct() to get 3.
  3. C. unionByName resolves columns by name. union and its alias unionAll resolve by position.
  4. D. A cross join returns every combination: 4 times 3 is 12.
  5. B. Broadcast the small dimension. A left outer join cannot broadcast its left side.

Have an idea, question, or feedback?

We'd genuinely like to hear from you.