Skip to content

Lesson 4 of 9 · 25m

Joins That Don't Multiply Your Rows

Merge cardinality, key dtypes, duplicate keys, validation, and the join diagnostics that prevent silent fanout.

The most dangerous join bug is not a failed join. It is a successful join that returns three times as many rows as the source table and feeds inflated revenue into a dashboard. pandas will happily do this because joins follow relational algebra, not your intentions. You have to state the expected cardinality and verify it.

Know the shape before and after

len(orders), len(customers)
merged = orders.merge(customers, on="customer_id", how="left", validate="m:1")
len(merged)

validate="m:1" says each order may match at most one customer, while customers may repeat across orders. If the customer extract accidentally contains duplicates, pandas raises before you ship inflated metrics. Validation is cheap compared with explaining why ARR doubled overnight.

The four join intents

  • how="left": keep every row on the left; enrich it if possible.
  • how="inner": keep only matches; often silently drops data.
  • how="outer": reconcile two universes; expect missingness on both sides.
  • how="right": almost never worth the readability cost — swap the inputs and use left.

Use indicator=True during reconciliation work. The _merge column tells you whether each row came from the left only, right only, or both, which is exactly what you need in anti-joins and audits:

m = new.merge(old, on="invoice_id", how="outer", indicator=True)
missing_in_new = m.loc[m["_merge"] == "right_only"]

Fanout comes from duplicate keys

orders["order_id"].duplicated().sum()
customers["customer_id"].duplicated().sum()

A many-to-many merge multiplies duplicates. Two order rows times three customer rows means six output rows. Sometimes fanout is legitimate — line items exploding into SKU-level facts — but then it should be explicit in naming and downstream aggregation. Accidental fanout usually comes from joining a dimension table at the wrong grain.

Keys must agree exactly

42 and "42" do not join. Neither do timestamps with different units or timezones, nor IDs with leading zeros lost in one system. Normalize keys before the merge and make the normalization visible:

orders["customer_id"] = orders["customer_id"].astype("string").str.strip()
customers["customer_id"] = customers["customer_id"].astype("string").str.strip()

Field notes

  • Add validate= to important merges; it turns assumptions into runtime checks.
  • Compare row counts and key null rates before and after every production join.
  • indicator=True is the fastest way to build anti-joins and reconciliation reports.
  • Do not deduplicate blindly; duplicates usually mean the extract grain is wrong.
  • A join that changes row count unexpectedly is a stop-the-line event, not a footnote.

Was this lesson helpful?

Sign in to rate