Skip to the page
Tecyfy

PySpark interview question · medium

What are Anti Join and Semi Join in Spark, and how do they work?

The short answerA left semi join returns the rows of the left table that have at least one match in the right table, with only the left table's columns and no duplicates from multiple matches.

The full answer

A left semi join returns the rows of the left table that have at least one match in the right table, with only the left table's columns and no duplicates from multiple matches. A left anti join returns the rows of the left table that have no match. They are Spark's join forms of EXISTS and NOT EXISTS.

customers = spark.createDataFrame([(1, "a"), (2, "b"), (3, "c")], "customer_id int, name string")
orders = spark.createDataFrame([(1,), (1,), (3,)], "customer_id int")

customers.join(orders, "customer_id", "left_semi").show()   # customers 1 and 3, once each
customers.join(orders, "customer_id", "left_anti").show()   # customer 2: never ordered
SELECT * FROM customers c LEFT SEMI JOIN orders o ON c.customer_id = o.customer_id;
SELECT * FROM customers c LEFT ANTI JOIN orders o ON c.customer_id = o.customer_id;

-- equivalent forms Spark rewrites to these joins
SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
SELECT * FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);

How they differ from an inner join

  • An inner join returns one row per matching pair, so a customer with three orders appears three times; a semi join returns them once.
  • Semi and anti joins return only left-side columns.
  • Spark can stop looking after the first match, so they can be cheaper.

How Spark runs them Like other joins: a broadcast hash join when the right side is small, otherwise a shuffle (sort-merge or shuffled hash join). Adaptive query execution and broadcast hints apply as usual.

Typical uses

  • Semi: keep only events for active customers; filter a large fact table by a list of keys.
  • Anti: find new records not yet in the target table (incremental loads); find orphan records, such as orders whose customer doesn't exist; data quality checks between systems.

The NULL trap NOT IN behaves differently from NOT EXISTS and anti joins when the subquery contains NULL. WHERE customer_id NOT IN (SELECT customer_id FROM orders) returns no rows at all if any orders.customer_id is NULL, because comparison with NULL is unknown. A left anti join or NOT EXISTS returns the expected rows, so prefer them.

Other notes

  • There are no right semi or anti joins in the DataFrame API; swap the tables.
  • For "keep rows that match a small list", isin() on a literal list is simpler than a semi join.
  • Anti joins are the standard way to check completeness between two systems: run one in each direction to list records missing on either side.

Last updated 16 October 2026

Sources

Where each fact comes from

  1. 1JOIN
  2. 2NULL semantics