Excelgoodies logo +65 3106 5185

LEARN THIS HANDS ON

Full Stack BI (On Cloud)

. Live Online FILLING FAST
View all upcoming batches
Azure Data Engineering Project: Load Only New or Updated Orders with Azure Data Factory

Azure Data Engineering Project: Load Only New or Updated Orders with Azure Data Factory

Most data teams start with a daily full reload and quickly hit the wall: long runtimes, blown SLAs, and pressure from the business when the orders table isn't ready by 8am. You don't actually need all the data every time — you need only the new or updated orders. This walkthrough shows how to implement that pattern in Azure Data Factory (ADF) in a way that’s reliable, debuggable, and production‑ready.

We’ll use a simple but realistic scenario: an e‑commerce platform writing orders into an operational SQL database, and a data team loading those orders into an Azure SQL Database (or dedicated SQL pool) for reporting. The requirement is to load only new or changed orders, several times per day, using Azure Data Factory.

Scenario: Incremental Orders from OLTP to Analytics

You have:

  • Source: Azure SQL Database SalesDB, table dbo.Orders (OLTP), with columns:
    • OrderID (PK, INT)
    • CustomerID
    • OrderDate
    • Status
    • TotalAmount
    • LastModifiedDate (datetime2, updated by the app on insert/update)
  • Sink: Azure SQL Database AnalyticsDB, table dbo.FactOrders, used by Power BI.
  • Requirement:
    • Run a pipeline every 15 minutes.
    • Load only orders that are new or updated since the last successful run.
    • Preserve history of previous values only when the source changes (type 1 slowly changing dimension semantics are fine for this fact table).

The anti‑pattern you’re replacing is a pipeline that truncates FactOrders and reloads everything from Orders on each run.

Design Options for Incremental Loads in ADF

For this scenario, three patterns are common in ADF:

  1. Watermark column in source (e.g. LastModifiedDate) + state stored in metadata.
  2. Change Tracking / Change Data Capture (CDC) in the source, consumed via ADF.
  3. Full extract + Delta computation in sink (staging + MERGE) – usually a fallback when you don’t control the source schema.

We’ll focus on pattern 1 with a watermark column, because:

  • It’s simple to reason about.
  • It’s supported for both Azure SQL Database and SQL Server.
  • It doesn’t require enabling CDC or Change Tracking on the source.

You can layer CDC or Change Tracking on top later if needed; the ADF side looks very similar.

Step 1: Prepare Source and Sink Tables

Source table

Assume your source table looks like this (simplified):

CREATE TABLE dbo.Orders
(
    OrderID          INT            NOT NULL PRIMARY KEY,
    CustomerID       INT            NOT NULL,
    OrderDate        DATETIME2(0)   NOT NULL,
    Status           NVARCHAR(20)   NOT NULL,
    TotalAmount      DECIMAL(18, 2) NOT NULL,
    LastModifiedDate DATETIME2(3)   NOT NULL
);

Key points:

  • LastModifiedDate must be monotonic per row (updated on insert and update).
  • It does not need to be unique across rows.

Sink table

In AnalyticsDB, create a table that will be upserted:

CREATE TABLE dbo.FactOrders
(
    OrderID          INT            NOT NULL PRIMARY KEY,
    CustomerID       INT            NOT NULL,
    OrderDate        DATETIME2(0)   NOT NULL,
    Status           NVARCHAR(20)   NOT NULL,
    TotalAmount      DECIMAL(18, 2) NOT NULL,
    LastModifiedDate DATETIME2(3)   NOT NULL
);

You’ll load into a staging table and then MERGE into FactOrders.

CREATE TABLE dbo.StgFactOrders
(
    OrderID          INT            NOT NULL,
    CustomerID       INT            NOT NULL,
    OrderDate        DATETIME2(0)   NOT NULL,
    Status           NVARCHAR(20)   NOT NULL,
    TotalAmount      DECIMAL(18, 2) NOT NULL,
    LastModifiedDate DATETIME2(3)   NOT NULL
);

Step 2: Decide Where to Store the Watermark

ADF needs to remember the last successful high watermark (max LastModifiedDate) between runs.

Common options:

  • Table in the sink database (simple, easy to query from SQL).
  • Azure Table Storage or Blob (works well when you have many pipelines).
  • ADF pipeline variables (not persistent across runs, so not suitable here).

We’ll use a control table in AnalyticsDB:

CREATE TABLE dbo.IncrementalState
(
    PipelineName      NVARCHAR(200) NOT NULL PRIMARY KEY,
    LastWatermarkUtc  DATETIME2(3)  NOT NULL
);

INSERT INTO dbo.IncrementalState (PipelineName, LastWatermarkUtc)
VALUES ('OrdersIncrementalLoad', '2000-01-01T00:00:00.000');

Using a very old default date ensures the first run picks up all existing rows.

Step 3: Build the ADF Pipeline Skeleton

Create a pipeline called pl_Orders_Incremental with these activities:

  1. Lookup – get the current watermark.
  2. Copy data – pull only new/updated orders into StgFactOrders.
  3. Stored procedure – MERGE from StgFactOrders into FactOrders.
  4. Stored procedure – update the watermark in IncrementalState.

We’ll walk through each part.

Step 4: Lookup the Current Watermark

Add a Lookup activity named GetWatermark:

  • Linked service: AnalyticsDB.
  • Query:
SELECT LastWatermarkUtc
FROM dbo.IncrementalState
WHERE PipelineName = 'OrdersIncrementalLoad';

Configure:

  • First row only: true.

In downstream activities, you’ll reference it as:

@activity('GetWatermark').output.firstRow.LastWatermarkUtc

ADF will treat this as a string; SQL will cast it back to datetime2 automatically in the query below as long as the format is ISO‑like (which SQL Server accepts).

Step 5: Copy Only Changed Orders to Staging

Add a Copy data activity named Copy_Orders_Incremental:

  • Source: linked service to SalesDB.
  • Sink: linked service to AnalyticsDB, table dbo.StgFactOrders.
  • Pre-copy script (on the sink):
TRUNCATE TABLE dbo.StgFactOrders;

This ensures staging only contains the current batch.

Source query with watermark

In the Source -> Use query box, parameterise the watermark:

SELECT
    OrderID,
    CustomerID,
    OrderDate,
    Status,
    TotalAmount,
    LastModifiedDate
FROM dbo.Orders
WHERE LastModifiedDate > @{activity('GetWatermark').output.firstRow.LastWatermarkUtc};

ADF will inline the expression before sending the query to SQL. Because LastWatermarkUtc is stored as datetime2(3) in IncrementalState and the expression is injected without quotes, SQL Server will treat it as a datetime2 literal.

Handling late updates and clock drift

The simple > comparison can miss rows if:

  • The source clock is slightly behind the sink clock.
  • Multiple rows share the same LastModifiedDate as the watermark.

To be safer, you can:

  1. Use >= and track the max watermark from the source query itself.
  2. De‑duplicate in the MERGE by comparing LastModifiedDate.

We’ll implement that in the MERGE and watermark update steps.

Step 6: MERGE from Staging into Fact Table

Add a Stored procedure activity named Merge_Orders using AnalyticsDB.

Create the stored procedure:

CREATE OR ALTER PROCEDURE dbo.usp_MergeFactOrders
AS
BEGIN
    SET NOCOUNT ON;

    MERGE dbo.FactOrders AS tgt
    USING dbo.StgFactOrders AS src
        ON tgt.OrderID = src.OrderID
    WHEN MATCHED AND tgt.LastModifiedDate < src.LastModifiedDate THEN
        UPDATE SET
            tgt.CustomerID       = src.CustomerID,
            tgt.OrderDate        = src.OrderDate,
            tgt.Status           = src.Status,
            tgt.TotalAmount      = src.TotalAmount,
            tgt.LastModifiedDate = src.LastModifiedDate
    WHEN NOT MATCHED BY TARGET THEN
        INSERT (
            OrderID,
            CustomerID,
            OrderDate,
            Status,
            TotalAmount,
            LastModifiedDate
        )
        VALUES (
            src.OrderID,
            src.CustomerID,
            src.OrderDate,
            src.Status,
            src.TotalAmount,
            src.LastModifiedDate
        );
END;

Notes:

  • The WHEN MATCHED predicate prevents older versions from overwriting newer ones if they reappear in staging.
  • If your source supports deletes and you need to reflect them, you’d add a WHEN NOT MATCHED BY SOURCE THEN ... clause, but that requires a way to detect deletions (e.g. soft‑delete flag or Change Tracking/CDC).

Configure the stored procedure activity to call dbo.usp_MergeFactOrders with no parameters.

Step 7: Update the Watermark Safely

You want to set the new watermark to the maximum LastModifiedDate actually processed from the source, not the current time.

Add another Stored procedure activity named Update_Watermark after Merge_Orders.

Create the procedure:

CREATE OR ALTER PROCEDURE dbo.usp_UpdateIncrementalState
    @PipelineName     NVARCHAR(200)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @NewWatermarkUtc DATETIME2(3);

    SELECT @NewWatermarkUtc = MAX(LastModifiedDate)
    FROM dbo.StgFactOrders;

    IF @NewWatermarkUtc IS NULL
    BEGIN
        -- No new rows this run; keep existing watermark
        RETURN;
    END;

    UPDATE dbo.IncrementalState
    SET LastWatermarkUtc = @NewWatermarkUtc
    WHERE PipelineName = @PipelineName;
END;

Configure the activity:

  • Stored procedure name: dbo.usp_UpdateIncrementalState.
  • Parameter @PipelineName value:
@pipeline().Pipeline

This ensures the watermark only moves forward when data actually arrived in staging.

Step 8: Control Flow and Failure Behaviour

Your pipeline flow should be:

  1. GetWatermark
  2. Copy_Orders_Incremental (on success of 1)
  3. Merge_Orders (on success of 2)
  4. Update_Watermark (on success of 3)

Key behaviours:

  • If Copy fails, StgFactOrders may be partially loaded, but Merge_Orders and Update_Watermark won’t run.
  • If Merge fails, watermark is not updated; the next run will re‑pull the same range. Because the MERGE only updates when src.LastModifiedDate is newer, reprocessing is idempotent.
  • If Update_Watermark fails, data is still merged. Next run will re‑pull the same rows; again, the MERGE predicate protects correctness at the cost of some extra work.

This pattern makes the pipeline at‑least‑once for each changed row but logically exactly‑once in the final fact table.

Step 9: Parameterise for Reuse

In a real project you’ll want to reuse the pattern for multiple tables.

Typical parameterisation:

  • Pipeline parameters:
    • p_SourceTableName
    • p_StagingTableName
    • p_FactTableName
    • p_PipelineKey (used in IncrementalState)
  • Stored procedures that accept table names and use QUOTENAME + dynamic SQL.

For example, a more generic watermark update procedure:

CREATE OR ALTER PROCEDURE dbo.usp_UpdateIncrementalState_Generic
    @PipelineName     NVARCHAR(200),
    @StagingTableName SYSNAME
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @Sql NVARCHAR(MAX);
    DECLARE @NewWatermarkUtc DATETIME2(3);

    SET @Sql = N'SELECT @WM = MAX(LastModifiedDate) FROM ' + QUOTENAME(@StagingTableName) + N';';

    EXEC sp_executesql
        @Sql,
        N'@WM DATETIME2(3) OUTPUT',
        @WM = @NewWatermarkUtc OUTPUT;

    IF @NewWatermarkUtc IS NULL
        RETURN;

    UPDATE dbo.IncrementalState
    SET LastWatermarkUtc = @NewWatermarkUtc
    WHERE PipelineName = @PipelineName;
END;

Call it from ADF with parameters based on pipeline parameters.

Step 10: Monitoring and Backfilling

Monitoring

Watch these in ADF Studio:

  • Pipeline run duration – should stabilise once incremental loads are in place.
  • Rows read/written in the Copy activity – validates that you’re only pulling deltas.

In SQL, you can quickly check:

SELECT COUNT(*) AS FactRowCount FROM dbo.FactOrders;
SELECT LastWatermarkUtc FROM dbo.IncrementalState WHERE PipelineName = 'OrdersIncrementalLoad';

Backfilling a new table

When you add a new table to the pattern:

  1. Set IncrementalState.LastWatermarkUtc to a suitably old date.
  2. Run the pipeline once to backfill.
  3. Confirm counts and data.
  4. Let the schedule take over for ongoing increments.

If you need to replay a time window (for example, after a source bug), you can temporarily set LastWatermarkUtc back to an earlier value and re‑run. Because of the LastModifiedDate comparison in the MERGE, you won’t corrupt existing data as long as the source’s LastModifiedDate values are consistent.

When You Might Prefer CDC or Change Tracking

The watermark pattern works well when:

  • You have a reliable LastModifiedDate column.
  • You don’t need hard deletes propagated.

If you need to capture deletes or avoid relying on an application‑managed timestamp, consider:

  • SQL Change Tracking: ADF supports reading change tracking tables via queries; you’d then MERGE based on the change type.
  • CDC‑based ingestion: e.g. using Azure Data Factory’s mapping data flow with CDC or external tools that land changes in a log table.

The downstream MERGE pattern stays similar; only the source query and staging schema become more complex.

Practical Takeaway

The core of an incremental orders pipeline in ADF is simple: a trusted watermark column, a persisted high watermark, and an idempotent MERGE that only applies newer changes. Once you have that pattern working for one table, you can standardise it across your project and stop paying the cost of full reloads every time the business wants fresher order data.

Editor's Note

This article reflects a shift from full-table reloads to watermark-based incremental loading patterns in Azure Data Factory, particularly valuable for teams running frequent refreshes from OLTP systems into analytical SQL stores.

Professionals who want to apply these patterns to their own data can explore Excelgoodies' Azure Data Engineering Course programme - taught live by instructors, with certification awarded once a real project is running at work.

Insights compiled through ongoing industry research and discussions within the Excelgoodies Analytics Community.

Azure

New

Next Batches Now Live

Power BIPower BI
SQLSQL
Power AppsPower Apps
Power AutomatePower Automate
Microsoft FabricMicrosoft Fabrics
AzureAzure Data Engineering
Explore Dates & Reserve Your Spot → Reserve Your Spot →