Sub topic 8
Deduplicating and upserting into silver with MERGE
This chapter assumes you can read basic SQL and PySpark. It also assumes you know what the bronze layer holds: raw, append-only rows with load metadata such as _ingested_at. It builds on the chapters about Delta Lake tables and incremental processing.
Why bronze needs deduplication
Bronze is append-only and replayable, so it keeps every copy of every record it receives. Duplicates reach it in several ways:
- A source system resends a file after a failure.
- An order changes status from
pendingtocompleted, and each change arrives as a new row with the sameorder_id. - A backfill reloads a date range that was already ingested.
- An upstream export contains the same record twice.
Silver should hold one current row per business key. The tool for this is MERGE INTO, which compares a set of incoming rows to a target table and then updates, inserts, or deletes in a single atomic Delta transaction. The usual silver pattern has two steps: reduce the incoming rows to one per key, then merge them into the target.
The shape of the pattern
Step 1: Pick the ordering rule
"Latest" needs a definition. You have three common choices:
| Ordering column | Meaning | Risk |
|---|---|---|
| `_ingested_at` | When Databricks loaded the row | Reflects arrival order, not event order. A late replay of an old file looks newest. |
| A source timestamp such as `updated_at` | When the source last changed the record | Best choice when it exists. Clocks and ties can still cause trouble. |
| A source sequence number or version | Monotonic counter from the source | Most reliable, but not always available. |
The examples below use _ingested_at, because that is the column the bronze step already creates. If your source supplies a trustworthy change timestamp or version, order by that instead. Add a second sort column to break ties, otherwise two rows with equal timestamps can be picked in a different order on each run.
Step 2: Create the silver table
The silver table keeps _ingested_at so the merge can detect stale updates later. Create it once, before the first merge:
CREATE TABLE IF NOT EXISTS main.silver.orders (
order_id STRING,
customer_id STRING,
order_ts TIMESTAMP,
amount DECIMAL(12,2),
status STRING,
_ingested_at TIMESTAMP
);Step 3: Write the MERGE
The query below keeps one row per order_id from bronze, then upserts it. QUALIFY filters on a window function, so you do not need a nested subquery for ROW_NUMBER.
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,
_ingested_at
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 AND s._ingested_at > t._ingested_at THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *Three details matter here:
WHERE order_id IS NOT NULLremoves rows that cannot be matched. A NULL never equals anything in theONclause, so such rows would be inserted again on every run.WHEN MATCHED AND s._ingested_at > t._ingested_atis the stale-update guard. A matched row that is not newer falls through all clauses and is left alone.UPDATE SET *andINSERT *map columns by name. This is short, but the source and target column names must agree. Prefer explicit column lists if the source schema changes often.
Why the pre-merge deduplication is required
Delta raises an error if more than one source row matches the same target row in an update. The error is DELTA_MULTIPLE_SOURCE_ROW_MATCHING_TARGET_ROW_IN_MERGE. The failure is deliberate, because the engine cannot know which of the two rows should win.
If you skip the QUALIFY step and bronze holds two rows for order_id = 1001, the merge fails once that key already exists in silver. When the key is new, both rows get inserted and you get duplicates in silver. The same bad input can therefore produce an error or silent duplicates, depending on the state of the target. Deduplicate the source first, every time.
Running the merge incrementally
The SQL above scans all of bronze on every run. That is fine for small tables. For larger ones, read only new bronze rows with Structured Streaming and run the merge once per micro-batch using foreachBatch:
from delta.tables import DeltaTable
from pyspark.sql import Window
from pyspark.sql import functions as F
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")
.select(
"order_id",
"customer_id",
F.col("order_ts").cast("timestamp").alias("order_ts"),
F.col("amount").cast("decimal(12,2)").alias("amount"),
"status",
"_ingested_at",
)
.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(condition="s._ingested_at > t._ingested_at")
.whenNotMatchedInsertAll()
.execute()
)
(
spark.readStream.table("main.bronze.orders")
.writeStream
.foreachBatch(upsert_to_silver)
.option("checkpointLocation", "/Volumes/main/sales/checkpoints/orders_silver")
.trigger(availableNow=True)
.start()
)Each micro-batch is deduplicated on its own, and the merge handles duplicates between the batch and the existing silver rows. Because the stale-update guard makes the merge idempotent, a batch that is retried after a failure produces the same result.
Reading bronze as a stream only works while bronze is append-only. If someone updates or deletes rows in bronze, the stream fails by default, which is another reason to keep that layer immutable.
Handling deletes
Sources often signal a delete with an operation column such as op = 'DELETE', not by removing a row. Add a clause that acts on it:
WHEN MATCHED AND s.op = 'DELETE' THEN DELETEPlace it before the update clause. Clauses are evaluated in order, and the first one whose condition is true is applied. If your silver table should keep history instead, set a is_deleted flag with an update. A third option is a slowly changing dimension design, which is outside this chapter.
WHEN NOT MATCHED BY SOURCE removes target rows that are missing from the source. Use it only when the source is a complete snapshot. With an incremental batch it would delete every row that was simply not in the batch.
Common errors and gotchas
- Wrong key. If the
ONcondition uses a column that is not unique in the target, one source row matches several target rows and the merge rewrites all of them. Confirm the key is unique with a query such asSELECT order_id, COUNT(*) FROM main.silver.orders GROUP BY order_id HAVING COUNT(*) > 1. - Composite keys. If an order line is identified by
order_idandline_no, partition the window by both columns and join on both. - Schema drift. A new column in the source breaks
UPDATE SET *unless schema evolution is enabled for the merge. Decide deliberately whether silver should accept new columns automatically. - Full scans on large targets. Without a condition that limits the target files, Delta may read much of the table to find matches. Adding a partition or date predicate to the
ONclause, where the business rules allow it, prunes files. Table layout choices are covered in the maintenance chapter. - Concurrent writers. Two merges that touch the same files can conflict and one will fail with a concurrent modification error. Run one writer per silver table, or retry on conflict.
Verifying the result
After a run, check three things:
- No key appears twice in silver, using the query shown above.
- Row counts make sense: silver should have at most as many rows as there are distinct non-null keys in bronze.
- Running the same job again changes nothing. Compare
DESCRIBE HISTORY main.silver.ordersbefore and after, and look at theoperationMetricsfor the latest MERGE. Updated and inserted row counts should be zero when no new data arrived.
Exercise
Bronze contains two rows for orderid 2001. Row A has status 'pending' and ingestedat 10:00. Row B has status 'completed' and ingestedat 11:00. Silver already holds order 2001 as 'completed' with ingested_at 11:00, and the next job run replays only Row A in its batch. Using the MERGE from this chapter, what is the status of order 2001 in silver afterward, and which clause explains it?
Show answer
The status stays 'completed'. Row A matches the existing key, but the clause "WHEN MATCHED AND s.ingestedat > t.ingestedat" is false because 10:00 is not greater than 11:00. No other clause applies to a matched row, so the target row is left unchanged. Without the guard, the replay would overwrite the current row with the stale 'pending' status.
Exercise
A teammate removes the QUALIFY step from the silver MERGE to make it simpler. Bronze holds two rows with order_id 3001, and 3001 is not yet in silver. What happens, and what changes if 3001 already exists in silver?
Show answer
When 3001 is not in silver, both rows match no target row, so both are inserted and silver now holds a duplicate key. When 3001 already exists in silver, both source rows match the same target row, and Delta fails the merge with a multiple-source-row-matching error. In both cases the fix is to reduce the source to one row per key before merging.