Sub topic 8
Validating joins and handling null keys
A join can run without errors and still return the wrong data. Two problems cause most of the damage: duplicate keys that silently multiply rows, and null keys that never match anything. This chapter shows how to make Polars check your assumptions, and how to decide what null keys should do. It assumes you can already write inner and left joins and know how on, left_on, and right_on choose the key columns.
Why unvalidated joins fail quietly
When you join, you usually have an expectation about the relationship between the tables. An orders table should look up each customer once. A table of customer profiles should match one account each. If that expectation is false, Polars still returns a result.
The most common failure is a duplicated key on the lookup side. Each matching pair produces one output row, so a left join can return more rows than the left table has.
import polars as pl
orders = pl.DataFrame({
"order_id": [100, 101, 102],
"customer_id": [1, 2, 3],
"amount": [30, 20, 50],
})
customers = pl.DataFrame({
"customer_id": [1, 2, 2],
"name": ["Ana", "Ben", "Ben (old)"],
})
joined = orders.join(customers, on="customer_id", how="left")
print(joined.height) # 4, although orders has only 3 rowsOrder 101 now appears twice, once for each customer row with id 2. A later sum over amount would count that order twice, and nothing warned you.
The validate parameter
DataFrame.join and LazyFrame.join accept a validate argument. It states the relationship you expect, and Polars raises an error if the data breaks it. The names read as left:right.
| validate | Left keys must be | Right keys must be | Typical use |
|---|---|---|---|
| "m:m" | any | any | Default. No check. |
| "m:1" | any | unique | Fact table joined to a lookup table |
| "1:m" | unique | any | Lookup table joined to detail rows |
| "1:1" | unique | unique | Two tables describing the same entities |
Apply m:1 to the join above:
try:
orders.join(customers, on="customer_id", how="left", validate="m:1")
except pl.exceptions.ComputeError as e:
print("validation failed:", e)The join raises a ComputeError that says the keys did not meet the expected relationship. The check runs before the result is returned, so you never see the inflated table.
On a LazyFrame the same argument works, but the error appears when you call collect(), not when you build the query. Put the collect() call inside your error handling.
Finding the offending keys
An error tells you the data is wrong but not which rows are wrong. To locate duplicates, filter with is_duplicated on the key column:
dupes = customers.filter(pl.col("customer_id").is_duplicated())
print(dupes) # both rows with customer_id 2Then decide how to fix them. Dropping rows is a data decision, so make it deliberately:
- If the extra rows are true duplicates, call
uniqueon the key. - If they are versions of one record, keep the newest by sorting first.
- If many rows per key is correct, the relationship is
m:mor1:m, and yourvalidatevalue or your downstream logic is what needs to change.
latest = customers.unique(subset="customer_id", keep="last", maintain_order=True)
checked = orders.join(latest, on="customer_id", how="left", validate="m:1")
print(checked) # 3 rows; order 102 has name null because customer 3 does not existWith keep="last" and maintain_order=True, the surviving row for id 2 is the last one in the original order, here "Ben (old)". If your data has no meaningful order, sort by a timestamp column before calling unique.
Notice that order 102 still has a null name. Validation checks uniqueness. It does not check that every key has a match. For that, use an anti join, which you met in the previous chapter:
orphans = orders.join(customers, on="customer_id", how="anti")
print(orphans) # order 102 onlyA short audit helps before any join whose result feeds a report:
def audit_keys(left: pl.DataFrame, right: pl.DataFrame, key: str) -> None:
print("left rows:", left.height)
print("left null keys:", left.select(pl.col(key).null_count()).item())
print("right null keys:", right.select(pl.col(key).null_count()).item())
print("right duplicated keys:",
right.select(pl.col(key).is_duplicated().sum()).item())
print("left rows without a match:",
left.join(right, on=key, how="anti").height)
audit_keys(orders, customers, "customer_id")For the tables above this reports 3 left rows, no null keys on either side, 2 duplicated key rows on the right, and 1 unmatched left row.
How null keys behave
In most Polars operations, null means "unknown", and two unknowns are not considered equal. Joins follow the same rule by default: a null key never matches another null key.
a = pl.DataFrame({"k": [1, None, 3], "left_val": ["x", "y", "z"]})
b = pl.DataFrame({"k": [1, None, 4], "right_val": [10, 20, 40]})
left = a.join(b, on="k", how="left")
inner = a.join(b, on="k", how="inner")
print(left) # (1, x, 10), (null, y, null), (3, z, null)
print(inner) # (1, x, 10) onlyThe row (null, y) survives the left join with a null right_val, because left joins keep every left row. The inner join drops it. In a full join, null-keyed rows from each side appear as separate, unmatched rows.
This default is usually what you want. Joining on a missing customer id should not attach the first anonymous customer to every anonymous order.
Making nulls match with nulls_equal
Sometimes null is a legitimate key value, for example a "no region" bucket present on both sides. Set nulls_equal=True to treat nulls as equal:
inner_nulls = a.join(b, on="k", how="inner", nulls_equal=True)
print(inner_nulls) # (1, x, 10) and (null, y, 20)With nulls_equal=True, every null on the left matches every null on the right. If both sides have many null keys, you get a many-to-many blow-up of exactly the kind that validate is meant to catch. Use it only when the null keys are few or are unique on at least one side.
Handling nulls before the join
Often the clearest approach is to take null keys out of the join and treat them explicitly:
with_key = a.filter(pl.col("k").is_not_null())
no_key = a.filter(pl.col("k").is_null())
matched = with_key.join(b, on="k", how="left")
print(matched) # (1, x, 10), (3, z, null)
print(no_key) # (null, y): handle these rows separatelyYou can then log the no_key rows, send them to a review table, or append them back with pl.concat([matched, no_key], how="diagonal"). The diagonal mode fills columns missing from one frame with null.
Another option is fill_null on the key, replacing nulls with a sentinel value such as -1 on both sides. This is equivalent to nulls_equal=True and carries the same risk. It also fails if the sentinel can appear as a real key, so prefer the explicit option.
A decision flow
Common mistakes
- Assuming a left join preserves the left row count. It only does so when the right keys are unique. Use
validate="m:1"to enforce that. - Choosing the direction backwards.
m:1constrains the right table. If the lookup table is on the left, you need1:m. - Treating validation as a match check. It does not detect keys missing from the other side. Use an anti join for that.
- Turning on
nulls_equal=Trueglobally to "fix" missing matches. This can hide a data-quality problem and multiply rows.
Exercise
A table events (many rows per user_id) is left joined to a table users, and the result has more rows than events. Which validate value would have caught this, and what are two other things you would check?
Show answer
Use validate="m:1", because users is the right-hand lookup table and its user_id must be unique. Two other checks: find the duplicated keys with users.filter(pl.col("user_id").is_duplicated()), and look for unmatched events with an anti join of events against users. You could also count null keys with null_count(), since nulls never match by default.
Exercise
Table a has keys [1, null] and table b has keys [1, null]. How many rows does an inner join on that key return by default, and how many with nulls_equal=True?
Show answer
By default it returns 1 row, the match on key 1, because null never equals null. With nulls_equal=True it returns 2 rows, because the null keys also match each other.