Tech challenge · Databricks

MERGE fails: multiple source rows matched

MediumDatabricks

A daily upsert into a Delta table fails with an error saying that multiple source rows matched and attempted to modify the same target row. The source is yesterday's change file for customers. What does the error mean, and how do you make the job reliable?

Think it through or sketch an answer first, then open the hint or the solution.

Show a hint

Look for the same customer_id more than once in the source file.

Show the solution

MERGE requires each target row to be matched by at most one source row; otherwise the result would be ambiguous. The change file contains several updates for the same customer. Deduplicate the source first, keeping the latest change per key, then merge.

Example (SQL)

MERGE INTO customers AS t
USING (
  SELECT * FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY changed_at DESC) AS rn
    FROM customer_changes
  ) WHERE rn = 1
) AS s
ON t.customer_id = s.customer_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;

Common mistakes

  • Removing the WHEN MATCHED clause to silence the error: the updates stop being applied.
  • Using dropDuplicates(['customer_id']) without ordering: you keep an arbitrary row, not the latest one.

Learn more

More Databricks challenges

Today's challenge and the full archive