Sub topic 7
Full, semi, anti, and cross joins
This chapter assumes you can already run inner and left joins with DataFrame.join, and that you know what a join key is. It covers four more join types. A full join keeps unmatched rows from both sides. Semi and anti joins filter one table using another. A cross join pairs every row with every row.
The tables used here
All examples continue from this setup. Order 102 belongs to customer 4, who is not in customers. Customers 2 and 3 have no orders.
import polars as pl
customers = pl.DataFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Cy"],
})
orders = pl.DataFrame({
"order_id": [100, 101, 102],
"customer_id": [1, 1, 4],
"amount": [30, 20, 50],
})Choosing by the question you are asking
Each join type answers a different question about the two tables. The diagram maps the question to the how argument.
| `how` | Rows returned | Columns returned | Needs keys |
|---|---|---|---|
| `full` | All matched rows, plus unmatched rows from both sides | Left and right columns | Yes |
| `semi` | Left rows that have at least one match | Left columns only | Yes |
| `anti` | Left rows that have no match | Left columns only | Yes |
| `cross` | Every left row paired with every right row | Left and right columns | No |
Full joins
A full join (also called a full outer join) combines the effects of a left join and a right join. Matched rows are combined. Unmatched rows from either table are kept, and the columns from the other table are filled with null.
full = orders.join(customers, on="customer_id", how="full")
print(full.sort("order_id", "customer_id_right"))The output has five rows:
- Orders 100 and 101 are matched to Ana.
- Order 102 is kept with
namenull, because customer 4 does not exist. - Ben and Cy are kept with
order_idandamountnull, because they have no orders.
The printed frame has two key columns, customer_id and customer_id_right. This is the default behavior for a full join. The left key is null on rows that came only from customers, and the right key is null on rows that came only from orders. Keeping both columns lets you see which side each row came from.
Most of the time you want one key column. Pass coalesce=True to merge them into one column that takes the left value when present and the right value otherwise:
full = orders.join(customers, on="customer_id", how="full", coalesce=True)
print(full.sort("customer_id", "order_id"))Now customer_id holds 1, 1, 2, 3, 4 and there is no customer_id_right column.
Using a full join for reconciliation
A full join is the natural tool for comparing two sources, such as a ledger and a bank export. Rows where one side is null are the discrepancies. With the default (non-coalesced) result you can filter on those nulls directly:
check = orders.join(customers, on="customer_id", how="full")
problems = check.filter(
pl.col("customer_id").is_null() | pl.col("customer_id_right").is_null()
)
print(problems.sort("order_id", "customer_id_right"))This returns order 102 and the two customers with no orders. With coalesce=True you would filter on a non-key column such as name or order_id instead.
Semi joins
A semi join keeps the rows of the left table that have at least one match in the right table. It does not add any columns from the right table, and it never duplicates a left row.
with_orders = customers.join(orders, on="customer_id", how="semi")
print(with_orders)The result is one row, Ana. She has two orders, but a semi join only tests whether a match exists. The columns are customer_id and name, the same as customers.
That is the difference from an inner join. An inner join of the same tables would return Ana twice, once per order, and would add order_id and amount. Use a semi join when you only want to filter, and you do not want the row count to change because of many-to-one matches.
Anti joins
An anti join is the opposite of a semi join. It keeps the left rows that have no match in the right table. Like a semi join, it returns only left columns.
no_orders = customers.join(orders, on="customer_id", how="anti")
orphan_orders = orders.join(customers, on="customer_id", how="anti")
print(no_orders) # Ben and Cy
print(orphan_orders) # order 102Which table is on the left decides the answer. Swapping the two tables turns "customers without orders" into "orders without customers". Both are useful data-quality checks.
You could write the same filters with is_in, for example customers.filter(~pl.col("customer_id").is_in(orders["customer_id"])). That works for a single key. Semi and anti joins are easier to extend to several key columns, and in lazy mode (see the last chapter of this tutorial) the query optimizer sees them as joins.
Cross joins
A cross join, also called a Cartesian product, pairs every row of the left table with every row of the right table. It takes no join keys, so you do not pass on.
import polars as pl
sizes = pl.DataFrame({"size": ["S", "M"]})
colors = pl.DataFrame({"color": ["red", "blue", "green"]})
variants = sizes.join(colors, how="cross")
print(variants) # 6 rows: every size with every colorThe row count is the product of the two row counts, 2 × 3 = 6. Typical uses are generating all combinations (products by store, dates by category) and building a complete grid that you then left join real data onto, so that missing combinations show up as nulls.
If both tables share a column name, the right-hand copy gets the suffix _right. You can change it with suffix=, as covered in the previous chapter.
Common mistakes
- Expecting right columns from a semi or anti join. These joins return only left columns. If you need right-side values, use an inner or left join.
- Forgetting that table order matters for anti and semi.
a.join(b, how="anti")andb.join(a, how="anti")return different rows. - Not handling the duplicate key column after a full join. Either use
coalesce=True, or readcustomer_id_righton purpose. - Passing
onto a cross join. A cross join has no keys. Leaveonout. - Assuming a stable order. Sort before comparing results or printing them in documentation.
Exercise
Using the customers and orders tables above, write one join that returns the names of customers who have never placed an order. Which rows does it return, and why does it not matter that Ana has two orders?
Show answer
customers.join(orders, on="customer_id", how="anti") returns Ben and Cy. An anti join keeps left rows with no match in the right table, and it returns only left columns. Ana matches, so she is dropped no matter how many orders she has. Her two orders do not create duplicate rows.
Exercise
A table of 4 warehouses and a table of 250 products are cross joined. How many rows result? Then the product table is left joined onto that result using real stock data. Why is this a useful pattern?
Show answer
The cross join returns 4 × 250 = 1,000 rows. Left joining real stock data onto this complete grid keeps every warehouse and product combination. Combinations with no stock record appear with null in the stock columns, instead of being missing from the output.