SQL Server
SQL for Data Engineering: Incremental Loads and MERGE
Apply new deliveries, corrections, and late arrivals with a transactional, repeatable upsert.
On this page
Learning objectives
- Apply new deliveries, corrections, and late arrivals with a transactional, repeatable upsert.
- Explain the input grain and output grain of this lesson’s query.
- Identify a repeatability, quality, or performance decision in the example.
- Verify the result against the supplied fictional fixture.
Prerequisites and setup
Prerequisites: SQL Server Foundations, including SELECT, WHERE, joins, aggregates, and NULL. Estimated time: 20–30 minutes. Run examples/sql-for-data-engineering/00_setup.sql in a disposable SQL Server 2019 or later database before running this lesson script.
Why this pattern matters
A full refresh rebuilds the target from all source rows; an incremental load processes only a bounded set of new deliveries. The example uses a delivery-sequence watermark, which captures a late business date because its delivery sequence is new. A production watermark must come from a source offset or a completeness barrier; MAX(identity) alone can skip out-of-order commits. The transaction locks the watermark, validates and quarantines the batch, updates a business key only when its source version is newer, inserts unseen keys, then advances the watermark. MERGE is supported T-SQL, but test source uniqueness, trigger behavior, and concurrency carefully; explicit UPDATE and INSERT are shown here as an alternative. Microsoft warns that MERGE can introduce complex concurrency issues and that separate DML may perform better under heavy concurrency. Ensure the source has at most one row per target key, and test locking and constraints under the intended isolation level. See Microsoft Learn: MERGE (Transact-SQL).
A data pipeline is a sequence of contracts. The source defines what a delivered row means; the staging step records how strings become typed values; validation states which rules a row passed; curated tables define their business grain; and reports state how measures are aggregated. Keeping these boundaries visible makes failures diagnosable. If a dashboard total changes, an engineer can compare each boundary and determine whether the source changed, parsing changed, a rule changed, or a consumer joined at the wrong grain.
Repeatability is part of correctness. A rerun should not create a second business event, silently skip a correction, or advance a checkpoint before target changes commit. Use a stable business key for identity, a source version or delivery sequence for ordering, and a documented policy for late data. Keep rejected rows with their source identifiers and reasons. A replayable batch is easier to investigate than a one-off manual correction because its inputs and decisions remain available.
- Watermark
- Upsert
- Commit
Read the query
The shared fixture starts with the same 20 fictional rows as the Python Foundations sales CSV. Text columns intentionally include blanks, invalid numbers, zero and negative quantities, a malformed decimal, and one missing business key. Three additional deliveries cover an exact redelivery, a correction, and a late-arriving transaction. The scripts preserve this source evidence; they do not change the CSV used by Python exercises. This lesson focuses on the shared source records and uses the same table and column names in all three languages. The query is a complete SQL Server example, not pseudocode. Read the filter, selected columns, and final order together: a filter defines which rows qualify, the projection defines what a reader can inspect, and ORDER BY defines the displayed sequence.
The script is stored at examples/sql-for-data-engineering/06_incremental_load.sql. Use the SQL viewer’s copy button to copy the exact source into SQL Server Management Studio or another SQL Server client. Run the setup script first. The viewer is read-only and does not execute queries or connect to a database. Outputs below come from the validated SQL Server run for this fixture.
/* Run 00_setup.sql first. A delivery-sequence watermark captures corrections and late business dates. */
SET NOCOUNT ON; SET XACT_ABORT ON;
SET ANSI_NULLS ON; SET ANSI_PADDING ON; SET ANSI_WARNINGS ON; SET ARITHABORT ON;
SET CONCAT_NULL_YIELDS_NULL ON; SET QUOTED_IDENTIFIER ON; SET NUMERIC_ROUNDABORT OFF;
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @last int,@next int;
SELECT @last=last_source_row_id FROM sqleng.Watermark WITH(UPDLOCK,HOLDLOCK) WHERE singleton_id=1;
SELECT @next=MAX(source_row_id) FROM (
SELECT source_row_id FROM sqleng.TransactionDelivery UNION ALL SELECT source_row_id FROM sqleng.ChangeFeed
) AS all_ids;
IF @next IS NULL OR @next<=@last BEGIN COMMIT; SELECT 'No new deliveries' AS load_status,@last AS watermark; RETURN; END;
CREATE TABLE #Batch(source_row_id int NOT NULL,transaction_id varchar(12) NULL,order_date_text varchar(20) NULL,
store varchar(40) NULL,product varchar(40) NULL,quantity_text varchar(20) NULL,unit_price_text varchar(20) NULL,
source_updated_at datetime2(0) NOT NULL);
INSERT #Batch SELECT * FROM sqleng.TransactionDelivery WHERE source_row_id>@last AND source_row_id<=@next
UNION ALL SELECT * FROM sqleng.ChangeFeed WHERE source_row_id>@last AND source_row_id<=@next;
;WITH ranked AS (
SELECT *,ROW_NUMBER() OVER(PARTITION BY transaction_id,CASE WHEN transaction_id IS NULL THEN source_row_id ELSE 0 END
ORDER BY source_updated_at DESC,source_row_id DESC) AS version_rank
FROM #Batch
), reasons AS (
SELECT *,CASE WHEN transaction_id IS NULL THEN 'Missing transaction_id'
WHEN TRY_CONVERT(date,order_date_text,23) IS NULL THEN 'Invalid order date'
WHEN NULLIF(LTRIM(RTRIM(store)),'') IS NULL THEN 'Missing store'
WHEN NULLIF(LTRIM(RTRIM(product)),'') IS NULL THEN 'Missing product'
WHEN TRY_CONVERT(int,quantity_text) IS NULL THEN 'Quantity is not an integer'
WHEN TRY_CONVERT(int,quantity_text)<=0 THEN 'Quantity must be positive'
WHEN TRY_CONVERT(decimal(10,2),unit_price_text) IS NULL THEN 'Unit price is not a decimal value'
WHEN TRY_CONVERT(decimal(10,2),unit_price_text)<0 THEN 'Unit price must not be negative'
ELSE NULL END AS rejection_reason
FROM ranked WHERE version_rank=1
)
INSERT sqleng.RejectedTransactions(source_row_id,transaction_id,rejection_reason)
SELECT source_row_id,transaction_id,rejection_reason FROM reasons WHERE rejection_reason IS NOT NULL;
;WITH typed AS (
SELECT *,TRY_CONVERT(date,order_date_text,23) AS order_date,TRY_CONVERT(int,quantity_text) AS quantity,
TRY_CONVERT(decimal(10,2),unit_price_text) AS unit_price,NULLIF(LTRIM(RTRIM(store)),'') AS clean_store,
NULLIF(LTRIM(RTRIM(product)),'') AS clean_product,
ROW_NUMBER() OVER(PARTITION BY transaction_id,CASE WHEN transaction_id IS NULL THEN source_row_id ELSE 0 END
ORDER BY source_updated_at DESC,source_row_id DESC) AS version_rank
FROM #Batch
), valid AS (
SELECT * FROM typed WHERE version_rank=1 AND transaction_id IS NOT NULL AND order_date IS NOT NULL
AND clean_store IS NOT NULL AND clean_product IS NOT NULL AND quantity>0 AND unit_price>=0
)
UPDATE target SET order_date=source.order_date,store=source.clean_store,product=source.clean_product,
quantity=source.quantity,unit_price=source.unit_price,source_updated_at=source.source_updated_at,source_row_id=source.source_row_id
FROM sqleng.FactSales AS target JOIN valid AS source ON source.transaction_id=target.transaction_id
WHERE source.source_updated_at>target.source_updated_at;
;WITH typed AS (
SELECT *,TRY_CONVERT(date,order_date_text,23) AS order_date,TRY_CONVERT(int,quantity_text) AS quantity,
TRY_CONVERT(decimal(10,2),unit_price_text) AS unit_price,NULLIF(LTRIM(RTRIM(store)),'') AS clean_store,
NULLIF(LTRIM(RTRIM(product)),'') AS clean_product,
ROW_NUMBER() OVER(PARTITION BY transaction_id,CASE WHEN transaction_id IS NULL THEN source_row_id ELSE 0 END
ORDER BY source_updated_at DESC,source_row_id DESC) AS version_rank
FROM #Batch
)
INSERT sqleng.FactSales(transaction_id,order_date,store,product,quantity,unit_price,source_updated_at,source_row_id)
SELECT source.transaction_id,source.order_date,source.clean_store,source.clean_product,source.quantity,source.unit_price,source.source_updated_at,source.source_row_id
FROM typed AS source WHERE source.version_rank=1 AND source.transaction_id IS NOT NULL AND source.order_date IS NOT NULL
AND source.clean_store IS NOT NULL AND source.clean_product IS NOT NULL AND source.quantity>0 AND source.unit_price>=0
AND NOT EXISTS(SELECT 1 FROM sqleng.FactSales AS target WITH(UPDLOCK,HOLDLOCK) WHERE target.transaction_id=source.transaction_id);
UPDATE sqleng.Watermark SET last_source_row_id=@next WHERE singleton_id=1;
COMMIT TRANSACTION;
SELECT COUNT(*) AS fact_count,CONVERT(decimal(12,2),SUM(revenue)) AS total_revenue,MAX(last_source_row_id) AS watermark
FROM sqleng.FactSales CROSS JOIN sqleng.Watermark;
END TRY
BEGIN CATCH
IF XACT_STATE()<>0 ROLLBACK TRANSACTION;
THROW;
END CATCH;Make types and null behavior explicit. Use TRY_CONVERT when source text may be malformed, then distinguish conversion failure from a legitimate zero. A decimal type should match the precision of the business measure. Dates should use an explicit input format. NULL does not equal an empty string and cannot be tested with =. A derived value should have a named rule and a documented fallback. These details matter at boundaries because a value that parses differently on two machines can change both validation and totals. Readable SQL helps reviewers follow the transformation, but readability alone does not guarantee performance. CTEs are query-scoped names and are not promises that SQL Server materializes an intermediate result. Inspect actual plans and row counts when work is repeated or large. Add an index only for a demonstrated access pattern and after considering write cost. Prefer a small, auditable example first; production tuning should follow measurements rather than assumptions based on syntax.
Practice
Run the setup script once, then run the lesson query. Inspect the output grain before changing the SQL. Complete the exercise by changing only a copy of the fixture, rerunning the query, and explaining how the result changed. Run the incremental script twice. Then add one new delivery with an older order_date but a higher delivery sequence. Run it again and confirm it inserts the late transaction without duplicating existing keys.
Expected result
First run: 13 facts, 538.70 revenue, watermark 23. Second run: no new deliveries and no duplicates.
Common mistakes
- Treating a display order as guaranteed without ORDER BY.
- Using a surrogate row ID as if it were the business key.
- Replacing an invalid value without retaining its source and reason.
- Assuming a readable query is automatically fast.
- Rerunning a write without checking its idempotency.
Knowledge check
- What does the watermark represent here?
- Why is MAX(identity) alone risky in production?
- When should the watermark advance?
It tracks the greatest completely processed delivery sequence in this fixture. A production checkpoint must represent a complete source boundary. Advance only in the transaction that commits target and rejection writes.
Operational notes
Before scheduling a load, define ownership for failed batches, retries, retention, permissions, monitoring, and recovery. Record a run identifier, the input boundary, start and end times, and counts for received, accepted, rejected, inserted, and updated rows. Reconcile measures as well as row counts. A successful SQL statement does not prove the entire pipeline succeeded if a later publication step failed. Keep credentials outside scripts and apply least privilege. Test a restore or replay procedure before relying on it during an incident.
These scripts are instructional examples, not production deployment templates. They use fictional data and an isolated sqleng schema. The setup script drops only tables in that teaching schema; never point it at a production database. SQL Server-specific syntax is labelled in the viewer. Other engines may differ in conversion functions, locking, transaction behavior, and upsert syntax.
Continue
Was this helpful?
What could be better?
Thanks — that helps me improve Javi Builds.
Continue learning
- Cheat sheetCheck SQL Server Table SizesMeasure SQL Server table row counts and storage usage, separate data from index space, and identify which tables are driving database growth.Open cheat sheet
- ArticleBuild an End-to-End SQL Data PipelineAssemble ingestion, staging, validation, quarantine, deduplication, curated facts, and reports.Read article
- ArticleSQL for Data Engineering: CTEsStructure a sales transformation as readable, query-scoped steps with CTEs.Read article
What should I build next?
I'm building Javi Builds around practical problems data engineers actually face. Tell me what you'd like to see next.
Stay in the loop
Get the Javi Builds updates you actually care about.
Check your inbox
I sent you a confirmation link. Your subscription will be active after you confirm it.