cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

How to prevent duplicate records when using MERGE INTO?

dataumer
New Contributor II

hello guys

What is the best way to handle a source dataset that contains multiple records for the same business key before performing a MERGE into a Delta table?

For example, the same customer ID may appear multiple times with different update timestamps.

Would using ROW_NUMBER() to retain the latest record be sufficient? How should we handle cases where multiple records have the same timestamp?

3 ACCEPTED SOLUTIONS

Accepted Solutions

SumeshKashyap
Honored Contributor

hi @dataumer 

MERGE expects at most one source row per key. If the same customer ID appears twice, it fails with "multiple source rows matched" or applies changes in an unpredictable order. So yes, ROW_NUMBER() is the right approach: cut the source down to the latest row per key, then merge that result.

MERGE INTO customers AS t

USING (

  SELECT *

  FROM customer_updates

  QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY updated_at DESC, ingest_seq DESC) = 1

) AS s

ON t.customer_id = s.customer_id

WHEN MATCHED AND s.updated_at > t.updated_at THEN UPDATE SET *

WHEN NOT MATCHED THEN INSERT *

Same-timestamp ties: ROW_NUMBER() picks one of the tied rows arbitrarily, so add a tie-breaker column to the ORDER BY (an ingest sequence number, file offset, or _metadata.file_modification_time) so the result is deterministic. If there's genuinely no way to order them, that's a data contract issue to raise with the source team.

A few other details:

- The s.updated_at > t.updated_at condition stops a late or replayed batch from overwriting newer data.

- In a streaming job, put the dedup and MERGE inside foreachBatch so each micro-batch is deduped before it merges.

- If you need every change kept as history (SCD2), use AUTO CDC / APPLY CHANGES in Lakeflow Declarative Pipelines with SEQUENCE BY updated_at. It handles the ordering for you.

Docs: https://docs.databricks.com/aws/en/delta/merge

View solution in original post

balajij8
Esteemed Contributor III

With the SQL semantics of MERGE, when more than one source row matches the same target row on the join key, the operation is ambiguous - Spark cannot tell which source row should win, so the MERGE either fails outright (multiple source rows matched and attempted to update the same target row error) or silently inserts duplicates when the duplicate rows happen to be unmatched new keys. You can pre process the source to eliminate the possibility of multiple matches before merging. MERGE deduplicates against the target, but never within the source - so a good merge can land duplicates that came in inside one batch.

Deduplicate the source to exactly one row per business key before the USING clause, and ROW_NUMBER instinct is right as it's the right pattern. You must add a deterministic tie breaker, because if two records share the same customer_id and the same updated_at, ROW_NUMBER alone picks a winner nondeterministically (winning row can flip between runs giving different results on a re run or a retry). You can chain secondary sort keys such as a sequence number, ingestion timestamp or a stable hash of the row so the same input always produces the same winner.

WITH ranked AS (
  SELECT *, ROW_NUMBER() OVER (
            PARTITION BY customer_id
            ORDER BY updated_at DESC,
                     batch_seq DESC,          -- tie breaker 1
                     to_json(struct(*)) DESC
         ) AS rn
  FROM   source_updates
)
MERGE INTO customers t
USING (SELECT * FROM ranked WHERE rn = 1) s
ON    t.customer_id = s.customer_id
WHEN MATCHED AND t.updated_at < s.updated_at THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *

View solution in original post

tajamulkhan
Esteemed Contributor
Hello

Yes, ROW_NUMBER() is a good approach, but the important part is making the deduplication deterministic.

Delta MERGE does not automatically deduplicate source records. Multiple source records matching the same target record can cause ambiguous update errors.

1. Deduplicate the source before MERGE

CREATE OR REPLACE TEMP VIEW clean_source AS
SELECT *
FROM staging_customers
QUALIFY ROW_NUMBER() OVER (
    PARTITION BY customer_id
    ORDER BY updated_at DESC, source_sequence DESC
) = 1;

For example, if customer 101 has two records with the same update timestamp but sequence numbers 5 and 6, the record with sequence 6 will be selected, assuming the sequence represents the actual event order.

2. Prevent older records from overwriting newer records

MERGE INTO target_customers AS t
USING clean_source AS s
ON t.customer_id = s.customer_id

WHEN MATCHED AND (
    s.updated_at > t.updated_at
    OR (
        s.updated_at = t.updated_at
        AND s.source_sequence > t.source_sequence
    )
)
THEN UPDATE SET *

WHEN NOT MATCHED THEN INSERT *;

3. Handle identical timestamps

If timestamps are identical, use a reliable secondary ordering field such as:

  • CDC sequence number.

  • Source transaction sequence.

  • Event version number.

If no reliable ordering field exists and the records contain conflicting values, I would quarantine those records rather than arbitrarily selecting one.

My recommendation is to combine deterministic source deduplication with conditional MERGE logic. Also, validate business key uniqueness in the target table and ensure ordering fields are non-null.

Avoid using dropDuplicates(["customer_id"]) alone because it does not guarantee that the latest record is retained.

Official references:

View solution in original post

3 REPLIES 3

SumeshKashyap
Honored Contributor

hi @dataumer 

MERGE expects at most one source row per key. If the same customer ID appears twice, it fails with "multiple source rows matched" or applies changes in an unpredictable order. So yes, ROW_NUMBER() is the right approach: cut the source down to the latest row per key, then merge that result.

MERGE INTO customers AS t

USING (

  SELECT *

  FROM customer_updates

  QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY updated_at DESC, ingest_seq DESC) = 1

) AS s

ON t.customer_id = s.customer_id

WHEN MATCHED AND s.updated_at > t.updated_at THEN UPDATE SET *

WHEN NOT MATCHED THEN INSERT *

Same-timestamp ties: ROW_NUMBER() picks one of the tied rows arbitrarily, so add a tie-breaker column to the ORDER BY (an ingest sequence number, file offset, or _metadata.file_modification_time) so the result is deterministic. If there's genuinely no way to order them, that's a data contract issue to raise with the source team.

A few other details:

- The s.updated_at > t.updated_at condition stops a late or replayed batch from overwriting newer data.

- In a streaming job, put the dedup and MERGE inside foreachBatch so each micro-batch is deduped before it merges.

- If you need every change kept as history (SCD2), use AUTO CDC / APPLY CHANGES in Lakeflow Declarative Pipelines with SEQUENCE BY updated_at. It handles the ordering for you.

Docs: https://docs.databricks.com/aws/en/delta/merge

balajij8
Esteemed Contributor III

With the SQL semantics of MERGE, when more than one source row matches the same target row on the join key, the operation is ambiguous - Spark cannot tell which source row should win, so the MERGE either fails outright (multiple source rows matched and attempted to update the same target row error) or silently inserts duplicates when the duplicate rows happen to be unmatched new keys. You can pre process the source to eliminate the possibility of multiple matches before merging. MERGE deduplicates against the target, but never within the source - so a good merge can land duplicates that came in inside one batch.

Deduplicate the source to exactly one row per business key before the USING clause, and ROW_NUMBER instinct is right as it's the right pattern. You must add a deterministic tie breaker, because if two records share the same customer_id and the same updated_at, ROW_NUMBER alone picks a winner nondeterministically (winning row can flip between runs giving different results on a re run or a retry). You can chain secondary sort keys such as a sequence number, ingestion timestamp or a stable hash of the row so the same input always produces the same winner.

WITH ranked AS (
  SELECT *, ROW_NUMBER() OVER (
            PARTITION BY customer_id
            ORDER BY updated_at DESC,
                     batch_seq DESC,          -- tie breaker 1
                     to_json(struct(*)) DESC
         ) AS rn
  FROM   source_updates
)
MERGE INTO customers t
USING (SELECT * FROM ranked WHERE rn = 1) s
ON    t.customer_id = s.customer_id
WHEN MATCHED AND t.updated_at < s.updated_at THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *

tajamulkhan
Esteemed Contributor
Hello

Yes, ROW_NUMBER() is a good approach, but the important part is making the deduplication deterministic.

Delta MERGE does not automatically deduplicate source records. Multiple source records matching the same target record can cause ambiguous update errors.

1. Deduplicate the source before MERGE

CREATE OR REPLACE TEMP VIEW clean_source AS
SELECT *
FROM staging_customers
QUALIFY ROW_NUMBER() OVER (
    PARTITION BY customer_id
    ORDER BY updated_at DESC, source_sequence DESC
) = 1;

For example, if customer 101 has two records with the same update timestamp but sequence numbers 5 and 6, the record with sequence 6 will be selected, assuming the sequence represents the actual event order.

2. Prevent older records from overwriting newer records

MERGE INTO target_customers AS t
USING clean_source AS s
ON t.customer_id = s.customer_id

WHEN MATCHED AND (
    s.updated_at > t.updated_at
    OR (
        s.updated_at = t.updated_at
        AND s.source_sequence > t.source_sequence
    )
)
THEN UPDATE SET *

WHEN NOT MATCHED THEN INSERT *;

3. Handle identical timestamps

If timestamps are identical, use a reliable secondary ordering field such as:

  • CDC sequence number.

  • Source transaction sequence.

  • Event version number.

If no reliable ordering field exists and the records contain conflicting values, I would quarantine those records rather than arbitrarily selecting one.

My recommendation is to combine deterministic source deduplication with conditional MERGE logic. Also, validate business key uniqueness in the target table and ensure ordering fields are non-null.

Avoid using dropDuplicates(["customer_id"]) alone because it does not guarantee that the latest record is retained.

Official references: