How to implement incremental loads in a Data Warehouse: step by step
This tutorial shows how to implement incremental loads in a Data Warehouse to load only the changes since the last run. It reduces load time, resource consumption and helps maintain consistency between the source and the Data Warehouse.
Prerequisites
- Basic knowledge of SQL and ETL.
- Access to a data source (e.g.: SQL Server, PostgreSQL) and to the Data Warehouse (e.g.: SQL Server, Azure SQL).
- Permissions to create tables and load jobs.
- A change indicator field in the source (e.g.: last_modified, timestamp) or a transaction log.
Step 1: Choose the incremental load strategy
Explain why to choose between Change Data Capture (CDC), timestamp-based or watermark. For an introductory/intermediate level, we use a last_modified field in the source (timestamp) and a watermark table in the Data Warehouse. Advantages: simple, works when there is a last_modified and there is no CDC.
Step 2: Create the target table and the watermark table
Create a target table in the Data Warehouse that includes a field for last_modified and the natural key. Also create a simple table to store the last watermark per entity.
-- Exemplo SQL Server
CREATE TABLE dim_product (
product_id INT PRIMARY KEY,
name NVARCHAR(200),
price DECIMAL(18,2),
last_modified DATETIME2
);
CREATE TABLE etl_watermark (
source_table NVARCHAR(100) PRIMARY KEY,
last_watermark DATETIME2
);
-- Inicializar watermark
INSERT INTO etl_watermark (source_table, last_watermark)
VALUES ('product', '1900-01-01');
Step 3: Extract only changes from the source
Use the watermark to fetch only rows with last_modified greater than the last stored value. This avoids scanning the entire source.
-- Exemplo de leitura incremental da origem (SQL Server ou PostgreSQL)
DECLARE @last DATETIME2;
SELECT @last = last_watermark FROM etl_watermark WHERE source_table = 'product';
SELECT product_id, name, price, last_modified
FROM source_db.dbo.product
WHERE last_modified > @last;
Step 4: Apply changes to the Data Warehouse (UPSERT)
Use MERGE or UPDATE/INSERT logic to apply only the changes. Check last_modified to avoid data regressions.
-- Exemplo MERGE (SQL Server)
MERGE INTO dim_product AS tgt
USING (
SELECT product_id, name, price, last_modified
FROM staging_product -- resultados da query de extração
) AS src
ON tgt.product_id = src.product_id
WHEN MATCHED AND src.last_modified > tgt.last_modified
THEN UPDATE SET name = src.name, price = src.price, last_modified = src.last_modified
WHEN NOT MATCHED BY TARGET
THEN INSERT (product_id, name, price, last_modified)
VALUES (src.product_id, src.name, src.price, src.last_modified);
Step 5: Safely update the watermark
After confirming the MERGE was successful, update the etl_watermark table with the largest last_modified processed. Important: update only after the commit to avoid data loss.
-- Exemplo de actualização do watermark
DECLARE @max_ts DATETIME2;
SELECT @max_ts = MAX(last_modified) FROM staging_product;
UPDATE etl_watermark
SET last_watermark = @max_ts
WHERE source_table = 'product';
Step 6: Handle common errors and ensure idempotency
Common errors: source clock with retroactive changes, rows with null last_modified, partial processing. Best practices: validate timestamps, use transactions so that the MERGE and the watermark update are atomic, log failures in an audit table.
-- Exemplo simples de auditoria de falhas
CREATE TABLE etl_audit (
id INT IDENTITY PRIMARY KEY,
source_table NVARCHAR(100),
run_ts DATETIME2 DEFAULT SYSUTCDATETIME(),
status NVARCHAR(20),
message NVARCHAR(1000)
);
-- Em caso de erro inserir uma linha com status = 'FAILED'
Verify the result
Confirm that the dim_product table contains only the updated records and that last_modified reflects the latest changes. Check etl_watermark for the new timestamp. Useful tests: insert a new record in the source, update an existing one and run the job; verify that only those rows appear in the dimension.
Conclusion
Implementing incremental loads with a watermark reduces ETL time and resources and is suitable when a last_modified field exists. Next steps: evaluate Change Data Capture for more complex loads, add reconciliation and latency metrics. Tip: start with a small set of tables and automate failure handling to gain confidence.