Sub topic 8
Deduplicating and upserting into silver with MERGE
This chapter assumes you can read SQL and PySpark, know what a bronze table is, and understand that Delta Lake tables support ACID transactions. It covers how to move bronze rows into silver without creating duplicates.
Why bronze has duplicates
Bronze is append-only. If a source system resends a file, or an order changes status and arrives again, bronze holds several rows for the same order_id. Silver should hold one current row per key. A plain INSERT INTO ... SELECT would copy every duplicate into silver, and rerunning the job would add them again.
MERGE INTO solves both problems. It compares incoming rows to the target on a key, then updates matches and inserts non-matches in one atomic transaction.
The two-step pattern
Do two things in one statement:
- Reduce the source to one row per key.
- Merge that reduced set into the target.
MERGE INTO main.silver.orders AS t
USING (
SELECT
order_id,
customer_id,
CAST(order_ts AS TIMESTAMP) AS order_ts,
CAST(amount AS DECIMAL(12,2)) AS amount,
status
FROM main.bronze.orders
WHERE order_id IS NOT NULL
QUALIFY ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY _ingested_at DESC) = 1
) AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *The subquery does the cleaning:
WHERE order_id IS NOT NULLremoves rows that cannot be matched to a key.- The
CASTcalls give columns proper types. ROW_NUMBER() ... ORDER BY _ingested_at DESCranks the rows for eachorder_id, newest first.QUALIFY ... = 1keeps only the newest.
The _ingested_at column was added during bronze ingestion. This is one reason to keep load metadata in bronze.
Why reruns are safe
The statement is idempotent. Running it twice on the same bronze data gives the same silver table. On the second run every key already exists, so the matched branch rewrites the same values and no rows are added.
Common errors
- Duplicates in the source. If two source rows match the same target row, Delta raises an error because the update would be ambiguous. Deduplicating in the
USINGsubquery prevents this. - A weak ordering column. If two rows share the same
_ingested_at, the winner is arbitrary. Add a tiebreaker such as a sequence number or file name when the source provides one. - Stale rows overwriting newer ones. The query picks the latest row within the bronze batch. It does not check whether silver already holds something newer. If late data can arrive, add a condition such as
WHEN MATCHED AND s.order_ts >= t.order_ts THEN UPDATE SET *. - Unqualified
UPDATE SET *. This copies every column from the source. It requires the source and target to have matching column names, so keep theSELECTlist aligned with the silver schema.
Doing it from PySpark
The same logic works with the Delta Python API, which is useful inside a foreachBatch streaming step.
from delta.tables import DeltaTable
from pyspark.sql import functions as F, Window
def upsert_to_silver(batch_df, batch_id):
w = Window.partitionBy("order_id").orderBy(F.col("_ingested_at").desc())
latest = (
batch_df
.where("order_id IS NOT NULL")
.withColumn("_rn", F.row_number().over(w))
.where("_rn = 1")
.drop("_rn")
)
(
DeltaTable.forName(spark, "main.silver.orders").alias("t")
.merge(latest.alias("s"), "t.order_id = s.order_id")
.whenMatchedUpdateAll()
.whenNotMatchedInsertAll()
.execute()
)Exercise
A MERGE into silver fails because several source rows match one target row. What is the cause and the fix?
Show answer
The bronze source holds more than one row for the same key. Deduplicate it in the USING subquery, for example with ROWNUMBER() partitioned by the key and ordered by ingested_at descending, keeping row 1.