Sub topic 8
Validating joins and handling null keys
This chapter assumes you can write a basic join with on= and know the left and inner join types. A join can return the wrong number of rows without raising any error. Two causes are duplicate keys and null keys. Polars lets you check for both.
Why joins can surprise you
Each left row is paired with every matching right row. If the right table has two rows for one key, the left row appears twice. Row counts grow, and totals computed afterward are inflated. This is a common source of silent bugs.
Checking key uniqueness with validate
The validate argument states what relationship you expect between the two tables. Polars checks it and raises an error if the keys break it.
| Value | Meaning | Rule enforced |
|---|---|---|
| `"m:m"` | many to many (default) | no check |
| `"1:m"` | one to many | left keys are unique |
| `"m:1"` | many to one | right keys are unique |
| `"1:1"` | one to one | both sides are unique |
Orders are many per customer, and customers should be unique. That makes "m:1" the right check for an orders-to-customers join.
import polars as pl
orders = pl.DataFrame({
"order_id": [100, 101, 102],
"customer_id": [1, 2, 2],
})
customers = pl.DataFrame({
"customer_id": [1, 2, 2],
"name": ["Ana", "Ben", "Benjamin"],
})
unchecked = orders.join(customers, on="customer_id", how="left")
print(unchecked.height) # 5, not 3: the two orders for customer 2 each match two names
try:
orders.join(customers, on="customer_id", how="left", validate="m:1")
except pl.exceptions.ComputeError:
print("validation failed: customers has duplicate customer_id values")Without validate, the result has 5 rows. With it, the duplicate customer 2 stops the join, and you can fix the data first. Use validate in pipelines where a duplicate key would mean bad input.
Null keys do not match by default
In Polars, a null join key matches nothing, including another null. A left row with a null key stays in a left join, but its right-side columns are null. In an inner join, that row is dropped.
orders = pl.DataFrame({
"order_id": [100, 101, 102],
"customer_id": [1, None, 2],
})
customers = pl.DataFrame({
"customer_id": [1, 2, None],
"name": ["Ana", "Ben", "Unknown"],
})
default = orders.join(customers, on="customer_id", how="left").sort("order_id")
equal = orders.join(
customers, on="customer_id", how="left", nulls_equal=True
).sort("order_id")
print(default) # order 101 has name null
print(equal) # order 101 has name "Unknown"Setting nulls_equal=True makes null keys match each other. Older Polars releases call this option join_nulls. If the option name raises a TypeError, check your installed version.
Choosing how to treat null keys
- Keep the default when a null key means "unknown", so it should not match anything.
- Use
nulls_equal=Trueonly when null is a real category that both tables share. - Filter or fill nulls before the join if you want explicit control, for example with
pl.col("customer_id").fill_null(0). - Check for nulls first with
orders["customer_id"].null_count().
Common errors
- Skipping
validateon a join that should never multiply rows. - Assuming a null key matches a null key.
- Checking only the row count after a join. Equal counts can hide a dropped row and a duplicated row that cancel out.
Exercise
You join orders (left) to a products table (right) on productid and expect each order to get exactly one product row. Which validate value do you pass, and what happens if products contains productid 7 twice?
Show answer
Pass validate="m:1", because many orders map to one product and the right side must be unique. Polars raises a ComputeError instead of returning a result, because the right keys are not unique.