Incremental load that does not duplicate rows

Keep a watermark: the newest modified time you have already loaded. Read only rows newer than it, remove duplicate keys inside the batch, and write them with MERGE on the business key instead of INSERT. Move the watermark in the same transaction as the merge. A retry then changes nothing, and a failed run leaves no half-load.

Get the project

Data engineers · ·

The problem

Your load reads the whole source every night and it is getting slow. So you switch to loading only what changed, with an INSERT. Then a run fails halfway, the scheduler retries it, and the same rows land twice. Or two runs overlap. The table now has duplicates and nobody knows since when. This Pattern is for data engineers who need a load that is safe to repeat.

Steps

Five steps inside one transaction: read the watermark, extract newer rows one per key, MERGE on the business key, move the watermark, commit.

The load as one transaction. Run it twice and the second run reads zero rows.

What the source needs first: a stable business key (id below) and a column that changes whenever a row changes (modified). Without both, a watermark load is not possible.

  1. Store the watermark in a control table. One row, one column. Start it at an old date so the first run loads everything.

    con.execute("CREATE TABLE watermark (last_modified TIMESTAMP)")
    con.execute("INSERT INTO watermark VALUES ('1970-01-01 00:00:00')")
    
  2. Open a transaction and read only newer rows, one per key. If a key appears twice in the batch, keep the latest version. MERGE expects at most one source row per target key; Microsoft’s documentation says so for Fabric Warehouse.

    CREATE OR REPLACE TEMP TABLE batch AS
    SELECT id, name, modified
    FROM read_csv('source.csv', header = true)   -- the project also declares the column types
    WHERE modified > (SELECT last_modified FROM watermark)
    QUALIFY row_number() OVER (PARTITION BY id ORDER BY modified DESC) = 1;
    
  3. Merge on the business key. Update only when the incoming row is newer, insert when the key is new. There is no delete clause on purpose: the batch is partial, and a partial batch must never delete.

    MERGE INTO target AS t
    USING batch AS b ON t.id = b.id
    WHEN MATCHED AND b.modified > t.modified THEN
        UPDATE SET name = b.name, modified = b.modified
    WHEN NOT MATCHED THEN
        INSERT VALUES (b.id, b.name, b.modified);
    
  4. Move the watermark in the same transaction. Use the newest modified of the batch, and keep the old value when the batch is empty.

    UPDATE watermark SET last_modified =
        COALESCE((SELECT max(modified) FROM batch), last_modified);
    
  5. Commit. On any error, roll back. The target and the watermark must succeed or fail together. If the watermark moves first and the merge then fails, those rows are lost for good.

  6. The same load in Fabric Warehouse T-SQL. Adapted from the example in Microsoft’s documentation, which reads the watermark from a control table in production. etl.Watermark and dbo.Customer are placeholder names.

    -- Adapt the names and test it in your own warehouse.
    SET XACT_ABORT ON;   -- any error rolls the whole transaction back
    BEGIN TRAN;
    
    DECLARE @Last datetime2 = (SELECT LastModified FROM etl.Watermark WHERE TableName = 'dbo.Customer');
    
    MERGE dbo.Customer AS target
    USING (
        SELECT CustomerID, CustomerName, ModifiedDate
        FROM stg.Customer
        WHERE ModifiedDate >= @Last          -- overlap on purpose; MERGE absorbs repeated rows
    ) AS source
    ON target.CustomerID = source.CustomerID
    WHEN MATCHED AND source.ModifiedDate > target.ModifiedDate THEN
        UPDATE SET CustomerName = source.CustomerName, ModifiedDate = source.ModifiedDate
    WHEN NOT MATCHED BY TARGET THEN
        INSERT (CustomerID, CustomerName, ModifiedDate)
        VALUES (source.CustomerID, source.CustomerName, source.ModifiedDate);
    
    UPDATE etl.Watermark
    SET LastModified = COALESCE((SELECT MAX(ModifiedDate) FROM stg.Customer WHERE ModifiedDate >= @Last), LastModified)
    WHERE TableName = 'dbo.Customer';
    
    COMMIT;
    

    etl.Watermark needs a seed row for the table, with an old date; if the row is missing, @Last is NULL and the merge reads nothing. If stg.Customer can hold the same CustomerID twice, deduplicate it first, as in step 2. Fabric Warehouse supports BEGIN TRAN, COMMIT TRAN and ROLLBACK TRAN.

  7. Prove it: run the load twice. The second run must report zero rows and leave the table untouched. The project below does exactly this.

The project

Get the project

incremental-load-no-duplicates is a small Python and DuckDB project with synthetic data. It contains the load above, the naive INSERT version for contrast, and 11 tests.

python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
python demo.py && python -m pytest -v

What the recorded run showed (full output in RUN_LOG.txt inside the project):

  • Naive append, each load crashing once after the INSERT and then retried: 12 rows for 4 distinct ids.
  • Watermark and MERGE, each load run twice: the second run extracted 0 rows. The target held 4 rows, with the updated name for id 2, and the watermark was 2026-11-03 08:00:00.
  • A failure before commit left the target and the watermark unchanged; the retry loaded the row once.

Terminal output of the demo and the test summary.

Real output of python demo.py and the test summary, DuckDB 2.0.1, 2026-11-29. Dates shortened for width.

Copy this prompt

To adapt the incremental load to another table, paste this into your AI assistant and name the SQL engine, business key and last-modified column. The assistant should draft the MERGE and checkpoint update for that engine, plus a test that reruns the load and checks the final state.

Write an idempotent incremental load for the table <table>.
Business key: <key column>. Change column: <modified column>.
Use a watermark control table and MERGE, not INSERT.
Deduplicate the batch to one row per key first (latest wins).
Move the watermark in the same transaction as the merge, after it.
Do not add a delete clause. Add a test that runs the load twice
and asserts the table and the watermark do not change.
Explain what happens with late rows and with deletes in the source.
Target engine: <DuckDB | Fabric Warehouse T-SQL | other>.

Check the answer for three things: a WHERE on the watermark, a single transaction around merge and watermark, and no WHEN NOT MATCHED BY SOURCE clause.

Test result

In DuckDB, rerunning the batch kept the table and watermark unchanged. An induced failure before commit rolled back the changes, and the retry completed the load.

Limits

  • Late rows are missed. A row that arrives with a modified older than the watermark is never read. The project has a test that shows it. Use a wider overlap window and rely on MERGE, or reload a recent period.
  • Boundary rows. With >, a late row whose timestamp equals the watermark is skipped (also tested). With >= plus MERGE, it is read again and absorbed. Microsoft’s mirrored-database example uses >= and suggests an overlapping window for continuously replicated data.
  • Deletes are invisible. A row deleted in the source never shows up in “newer than”. Use soft deletes, change data capture or a periodic full comparison. Only use WHEN NOT MATCHED BY SOURCE THEN DELETE against a complete source, never a partial batch.
  • Duplicate keys in a batch. The project removes duplicate keys before MERGE. Microsoft’s documentation only warns about it for Fabric Warehouse. Deduplicate the batch yourself, and break ties on the change column with a second column so the winner is repeatable.
  • Clock differences. If the source stamps modified with a different clock than the loader, rows can fall behind the watermark. Use the source’s own value, not the loader’s time.
  • Missing values. A row with a NULL modified never passes the filter and is skipped silently. Reject or count such rows before the load.
  • Concurrent writers in Fabric Warehouse. It locks at table level, and two transactions that MERGE the same table can conflict. The documentation reports errors 24556 and 24706 and advises retry logic with a delay. Do not run two loads of the same table at once.

Sources

Author

Rodrigo Lombana Reina, data engineer. Personal opinions. Checked against the documentation on 2026-11-29.

Questions

How do I do an incremental load without duplicate rows?

Keep a watermark, the newest modified time already loaded. Read only newer rows, keep one row per key in the batch, and write them with MERGE on the business key instead of INSERT, in DuckDB 2.0.1 or Fabric Warehouse T-SQL. Move the watermark in the same transaction as the merge, so a retry changes nothing and a failed run leaves no half-load.

What is an idempotent load?

A load you can run twice and get the same table. With a watermark and MERGE on the business key, a repeated run finds no newer rows, or finds the same rows and overwrites them with identical values. In the recorded DuckDB 2.0.1 run, the second run extracted 0 rows and the target stayed at 4 rows.

Why does my pipeline duplicate rows after a retry?

Because a plain INSERT has no memory. If a run fails after the INSERT and the scheduler retries, the same rows land twice. In the recorded DuckDB 2.0.1 demo, each load crashed once after the INSERT and was retried, ending with 12 rows for 4 distinct ids. A MERGE on the business key matches existing rows instead.

Should the watermark filter use > or >=?

With plain INSERT, > avoids repeated rows but can lose late rows that share the watermark's timestamp. With MERGE, >= is safe because repeated rows are matched and not duplicated. Microsoft's Fabric example uses >= for that reason, and its mirrored-database example suggests an overlapping window for continuously replicated data.

Why must the watermark move in the same transaction as the MERGE?

Because the target and the watermark must succeed or fail together. If the watermark moves first and the merge then fails, those rows are lost for good. In Fabric Warehouse T-SQL, SET XACT_ABORT ON with BEGIN TRAN and COMMIT rolls everything back on any error. In the recorded DuckDB run, a failure before commit left both unchanged.

Does a watermark load catch deleted rows?

No. A row deleted in the source never appears in a query for newer rows. Use soft deletes, change data capture or a periodic full comparison. Only use WHEN NOT MATCHED BY SOURCE THEN DELETE against a complete authoritative source, never against a partial batch, because it would delete every row the batch did not contain.

What happens if two rows with the same key reach MERGE?

Microsoft's documentation says MERGE expects at most one source row per target key for Fabric Warehouse, so deduplicate the batch first. The project does it with row_number, keeping the latest version per id. What each engine does with duplicate keys was not tested here. Break ties on the change column with a second column so the winner is repeatable.

Can two loads of the same Fabric Warehouse table run at once?

Avoid it. Fabric Warehouse locks at table level, and two transactions that MERGE the same table can conflict. Microsoft's transactions documentation reports errors 24556 and 24706 and advises retry logic with a delay. MERGE is generally available in Fabric Data Warehouse per the T-SQL surface area page; the T-SQL in the article was not executed.

Portrait of Rodrigo Lombana Reina

Rodrigo Lombana Reina, data engineer. Data problems solved, step by step.

About Rodrigo · The opinions and texts on this site are my own.

My LinkedIn profile