Incremental models and snapshots
Part of the free LogicWiz Data Engineering course, Module 8: Transformation as code: dbt. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:50 on Monday and the 9:00 run of fct_orders is still going. In January the hourly rebuild took two minutes. With a year of history it takes fifty, and the warehouse bill has doubled. Tess has a second question: which city did customer 18 live in when he ordered on 7 June? Dana's database only knows where he lives today.
You'll learn to
- Build an incremental model with is_incremental() and a unique_key
- Catch late rows with a lookback window
- Say what an incremental run sends and what its merge costs
- Keep the history a source overwrites, with a snapshot
Learn
Fifty minutes for one hour of orders
A table model rebuilds all of history on every run, and almost none of it changed since the last one. You pay fifty minutes to rewrite a year of orders for one hour of new ones.
Think of a long book. You do not start from page one every evening: you leave a bookmark.
dbt can do the same. It builds the whole table once. On every later run it reads only the rows that are new or changed, and adds them to the table it already has. That is an incremental model. The bookmark is the watermark from Module 6.
An ordinary model with three additions
The file models/fct_orders.sql as five stacked parts: a config line naming the materialisation and the unique key, the select, an if block that adds a filter, the model's own table inside that filter, and a line that keeps the newest row per order.
Read it top to bottom: it is one SQL file. The violet, teal and blue parts are what make it incremental. The grey parts are an ordinary model.
Three additions to an ordinary model
Look at the coloured boxes.
- The config line says: keep a real table, and
order_idis the unique key, the column that tells one order from another. - The
ifblock wraps a filter.is_incremental()is false on the first run, because there is no table yet, so the model reads everything. On later runs it is true and the filter is in. {{ this }}is the model's own table. The filter asks it for the latestupdated_atit holds. That value is the table's high-water mark: only newer rows pass.
The rows one run picks up are called its batch. The last line is the dedup from Lesson 2.4: if a batch holds two versions of one order, the model keeps the newest.
Run it: four days, four runs
import duckdb
import minidbt
# The raw table starts with the 1 June drop; each day's drop is appended to it.
duckdb.sql("create schema shop")
duckdb.sql("create table shop.orders as select * from 'landing/orders/2025-06-01.csv'")
project = minidbt.Project(models={'fct_orders': """
{{ config(materialized='incremental', unique_key='order_id') }}
select order_id, customer_id, status, updated_at
from {{ source('shop', 'orders') }}
{% if is_incremental() %}
where updated_at > (select max(updated_at) from {{ this }})
{% endif %}
qualify row_number() over (partition by order_id order by updated_at desc) = 1
"""})
project.run() # 1 June: the table does not exist yet, so a full build
for day in ['02', '03', '04']:
duckdb.sql(f"insert into shop.orders select * from 'landing/orders/2025-06-{day}.csv'")
project.run() # later days: only rows changed since the last run
print(duckdb.sql("select count(*), count(distinct order_id) from fct_orders").fetchone())
print(project.compile('fct_orders', incremental=True))
Watch the brackets in the log. The first run says SELECT 6: a full build. The later ones say INSERT 8, INSERT 7 and INSERT 8: only the rows past the high-water mark. The last print is the SQL a later run sends. The filter is in, because is_incremental() is true.
Run by run: only the new rows move
Four daily runs of the incremental model: each day's drop on the left with its new and changed orders, and the fct_orders table on the right growing from 6 to 12, 17 and 22 rows while its high-water mark moves forward.
1 June, the first run. There is no table yet, so
is_incremental()is false and the model reads everything. Six orders go in. The high-water mark is now 1 June, 19:07.2 June. All 8 rows of the new drop are past the mark. Six are new orders. Two are orders 1002 and 1006, now
shipped: their old rows are replaced, not doubled. 12 rows for 12 orders.3 June. Seven rows are past the mark: 5 new orders, and new versions of orders 1008 and 1012. The other 10 rows of the table are left alone.
4 June. Eight rows are past the mark: 5 new orders and 3 changed ones. The table holds 22 rows for 22 orders, and each run handled only that day's rows.
Read each step left to right: what arrived that day, then the table after the run. The mark is the latest updated_at the table holds.
Remember: an incremental model builds everything once. After that it reads only the rows past its own high-water mark, and the unique key lets it replace a changed row instead of adding a second one.
Take the key away
What does the unique key buy you? Take it out of the config and run the same four days.
Without a key, dbt cannot tell which old row a new version belongs to. All it can do is append: add every row of the batch to the end of the table.
Before you run it, guess. The source has 22 different orders. Will the table have 22 rows?
The same model without a unique_key
import duckdb
import minidbt
duckdb.sql("create schema shop")
duckdb.sql("create table shop.orders as select * from 'landing/orders/2025-06-01.csv'")
model = """
{{ config(materialized='incremental', unique_key='order_id') }}
select order_id, customer_id, status, updated_at
from {{ source('shop', 'orders') }}
{% if is_incremental() %}
where updated_at > (select max(updated_at) from {{ this }})
{% endif %}
qualify row_number() over (partition by order_id order by updated_at desc) = 1
""".replace(", unique_key='order_id'", "")
project = minidbt.Project(models={'fct_orders': model}, quiet=True)
project.run()
for day in ['02', '03', '04']:
duckdb.sql(f"insert into shop.orders select * from 'landing/orders/2025-06-{day}.csv'")
project.run()
print(duckdb.sql("select count(*), count(distinct order_id) from fct_orders").fetchone())
duckdb.sql("select * from fct_orders where order_id = 1002").show()
It prints 29 rows for 22 orders. Order 1002 is there twice, placed and shipped, so every count and every revenue sum over this table is too high. With the key, dbt replaces instead. Here it deletes the old rows and inserts the batch (delete+insert). On Snowflake, BigQuery or Databricks it sends one MERGE, which updates the rows that match and inserts the rest.
"Incremental" without unique_key means "append". Every changed order adds a row, and nothing fails. The batch must also hold each key once. On Snowflake a MERGE stops with Duplicate row detected during DML action when two batch rows match one table row, and delete+insert would quietly insert both. So the model keeps only the newest version of each order.
What a later run sends to the warehouse
After the first run, every run of the model does the same four things:
- Compile the SELECT with
is_incremental()true, so the filter is in. - Stage the batch: put the result in a temporary table,
fct_orders__dbt_tmp. - Compare columns of the batch and the table. A setting called
on_schema_changedecides what a difference means. By default, a new column is left out of the table without a word. - Apply the batch with one or two statements, then commit. Which statements depends on the model's strategy: Lesson 8.6 shows the SQL of each.
The first run skips all four and builds the whole table.
One incremental run of fct_orders on dbt-postgres
A sequence between dbt and the warehouse: dbt compiles the incremental branch, creates a temporary table holding the batch, compares its columns with the table, deletes the rows whose keys arrive again, inserts the batch and commits.
Read it top to bottom: the numbers are the four steps above. minidbt runs the same steps in DuckDB. On Snowflake, BigQuery or Databricks the two statements after the divider are one MERGE.
Order 1016 arrives two days late
Now the fifth day. Order 1016 was placed on 3 June at 12:10, but it only reaches the 5 June drop, still stamped 3 June.
By then the table's high-water mark is 4 June, 23:17. The filter asks for rows newer than that. Order 1016 is older, so it is skipped. Tomorrow the mark is later still. The order is never loaded, and nothing fails.
The fix is a lookback window: on every run, reach back behind the mark and reprocess those days too, with >= max(updated_at) - interval 2 day. The overlap is safe, because the unique key replaces rows that are already there instead of adding them.
Catch the late order with a lookback
import duckdb
import minidbt
def run_days(model):
duckdb.sql("drop schema if exists shop cascade")
duckdb.sql("drop table if exists fct_orders")
duckdb.sql("create schema shop")
duckdb.sql("create table shop.orders as select * from 'landing/orders/2025-06-01.csv'")
project = minidbt.Project(models={'fct_orders': model}, quiet=True)
project.run()
for day in ['02', '03', '04', '05']:
duckdb.sql(f"insert into shop.orders select * from 'landing/orders/2025-06-{day}.csv'")
project.run()
return duckdb.sql("select count(*) from fct_orders where order_id = 1016").fetchone()[0]
plain = """
{{ config(materialized='incremental', unique_key='order_id') }}
select order_id, customer_id, status, updated_at
from {{ source('shop', 'orders') }}
{% if is_incremental() %}
where updated_at > (select max(updated_at) from {{ this }})
{% endif %}
qualify row_number() over (partition by order_id order by updated_at desc) = 1
"""
lookback = plain.replace("(select max(updated_at) from {{ this }})",
"(select max(updated_at) - interval 2 day from {{ this }})")
print("order 1016 without a lookback:", run_days(plain))
print("order 1016 with a 2-day lookback:", run_days(lookback))
Order 1016 has 0 rows without a lookback and 1 row with it. Pick a lookback longer than the latest you have ever seen a row arrive. It costs a little: each run reprocesses two days instead of one, still tiny next to rebuilding all of history.
The watermark, a late row and a lookback
A timeline of incremental runs: the watermark moves forward after each run, a late row arrives behind it and is missed, and a lookback window reaches back far enough to catch it.
Press Run the next load a few times, then A late row arrives: the Missed counter goes up. Now widen the Lookback slider and run again. The simulator calls the high-water mark the watermark, as Module 6 does.
Remember: > max(updated_at) never looks behind the high-water mark. A lookback does, and the unique key makes the overlap harmless.
The merge reads far more than it writes
One more cost hides in step 4. To apply a batch, a MERGE must find each batch row's partner in the table. Unless something narrows the search, it reads the whole table.
Work it through for fct_events, which holds a year of events:
- The table is about 2,000 GB. Each batch is 5 GB.
- A plain merge reads 2,000 + 5 = 2,005 GB to change 5.
- Tell the merge that matches can only be in the last 7 days, at about 5.5 GB a day: 7 x 5.5 = 38.5 GB.
- Add the 5 GB batch: about 43.5 GB.
That hint is a config called incremental_predicates. BigQuery bills the scan, and Delta also rewrites every file holding a matched row.
GB read by one run of a year-long fct_events
Bars compare one run of a 2,000 GB event table with a 5 GB batch: about 2,000 GB for a full rebuild, 2,005 GB for a merge with no predicates, 43.5 GB for a merge limited to the last 7 days, and 5 GB for a plain append.
Compare the second bar with the third: the same merge, with and without the hint. The hint is only safe if no batch row can match a table row outside it, so pick the window the way you picked the lookback. Partition or cluster the table by that date column, so the engine can skip the rest.
The city the shop's database forgot
Now Tess's question. On 9 June customer 18 moved from Berlin to Munich, and Dana's app overwrote his row. Berlin is gone from the source, and no incremental model can bring it back.
A dbt snapshot is a table that keeps what the source forgets. Think of taking a photo of the customers table after every load. On each run dbt compares the source with its last photo. For a row that changed, it closes the old version by filling in dbt_valid_to, and adds the new version with its dbt_valid_from.
That is the type 2 history table from Lesson 5.4, maintained for you. A snapshot only sees what changed between two runs, so run it at least as often as the source changes.
Customer 18 moves, and the snapshot keeps both cities
The shop's customers table beside the snapshot table over three moments: the first snapshot stores a current Berlin row, the shop overwrites Berlin with Munich, and the second snapshot closes the Berlin row and adds a current Munich row.
The first snapshot. dbt copies all 30 customers and marks every row current:
dbt_valid_tois empty. For customer 18 that row says Berlin, valid from 15 April.9 June, 08:30: he moves. The shop overwrites the row in place. Berlin is gone from the source. The snapshot has not run yet, so it still shows the old picture.
The second snapshot. dbt sees a newer
updated_atfor customer 18. It closes the Berlin row at 9 June, 08:30, and adds a Munich row that starts at the same moment. Nothing is deleted: 31 rows.
Read each step left to right: the shop's row, then the snapshot's rows for the same customer. A row whose end is NULL is the current version.
Snapshot customer 18's move
import duckdb
import minidbt
duckdb.sql("create schema shop")
duckdb.sql("create table shop.customers as select * from 'data/customers.csv'")
# Before 9 June, customer 18 still lived in Berlin
duckdb.sql("update shop.customers set city = 'Berlin', updated_at = '2025-04-15 10:00:00' where customer_id = 18")
project = minidbt.Project(models={}, snapshots={
'customers_snapshot': {
'sql': "select customer_id, name, city, updated_at from {{ source('shop', 'customers') }}",
'unique_key': 'customer_id',
'updated_at': 'updated_at',
},
})
project.snapshot() # first picture: 30 rows, all current
# 9 June: the shop overwrites the row in place
duckdb.sql("update shop.customers set city = 'Munich', updated_at = '2025-06-09 08:30:00' where customer_id = 18")
project.snapshot() # second picture: close Berlin, add Munich
duckdb.sql("""
select customer_id, city, dbt_valid_from, dbt_valid_to
from customers_snapshot where customer_id = 18 order by dbt_valid_from
""").show()
The first project.snapshot() takes the picture before the move, the second one after it. The query at the end prints both versions of customer 18.
customers_snapshot for customer 18
| customerid | city | dbtvalidfrom | dbtvalidto |
|---|---|---|---|
| 18 | Berlin | 2025-04-15 10:00:00 | 2025-06-09 08:30:00 |
| 18 | Munich | 2025-06-09 08:30:00 | NULL (current) |
Now Tess has her answer. Order 1039 was placed on 7 June, inside the Berlin row's window. Join orders to the snapshot on customer_id and order_ts >= dbt_valid_from and (order_ts < dbt_valid_to or dbt_valid_to is null).
The same snapshot in real dbt (1.9 and later)
Runs with dbt:
# snapshots/customers_snapshot.yml
snapshots:
- name: customers_snapshot
relation: source('shop', 'customers')
config:
unique_key: customer_id
strategy: timestamp
updated_at: updated_at
Run it with dbt snapshot (or dbt build), usually right after each load. Older projects define snapshots in a .sql file inside {% snapshot %} tags.
Numbers to remember
| Name | Default or version | What it does |
|---|---|---|
| isincremental() | false on the first run and with --full-refresh | Decides whether the filter is in. Run --full-refresh once when the model's logic changes. |
| uniquekey | none: the run appends | Names the row a new version replaces. |
| incrementalstrategy | merge on Snowflake, BigQuery and Databricks | How the batch goes in. Also delete+insert, append, and insertoverwrite, which replaces whole partitions with no key matching (BigQuery, Spark). |
| microbatch strategy | dbt 1.9 | Processes one time slice (say a day) per batch and can backfill a date range. |
| onschemachange | ignore | ignore leaves a new column out and fails if a column disappeared. appendnewcolumns adds new ones. syncallcolumns adds and drops, types included. fail stops. None of them backfills old rows. |
| incrementalpredicates | none | Conditions on the table side of the merge, such as DBTINTERNALDEST.eventdate = dateadd(day, -7, currentdate) on Snowflake. |
| Snapshot strategy | timestamp or check | timestamp spots a change by a newer updatedat. check compares the checkcols you list, reading them for every current row on every run, so list columns instead of all. Use it when the source has no trustworthy updatedat. |
| dbtscdid, dbtupdatedat | added by real dbt | A key dbt builds per version, and when dbt recorded it. |
| dbtvalidtocurrent | dbt 1.9; NULL unless set | For example '9999-12-31', so range joins need no or ... is null. |
| harddeletes | dbt 1.9; ignore | ignore: a row deleted at the source stays current for ever. invalidate closes it. newrecord adds a row flagged dbtisdeleted. |
What changed at SwiftKart
fct_orders is now incremental. The hourly run reads only what changed since the last run, plus a two-day lookback, and replaces changed orders by their key. It no longer rewrites a year of history every hour.
Tess's second question has an answer too. A snapshot of customers runs after every load, so the warehouse knows customer 18 lived in Berlin on 7 June.
One thing still bothers Nora. The rule for which orders count as revenue is copied into five models. Lesson 8.5 puts it in one place with a macro, and runs real dbt on a laptop.
In one line
An incremental model reads only rows past its high-water mark, replaces changed rows by unique_key and looks back for late ones; a snapshot keeps the history a source overwrites.
Interview corner
How does a dbt incremental model work?
On the first run, or with --full-refresh, it builds the whole table. On later runs is_incremental() is true, so a filter such as updated_at > (select max(updated_at) from {{ this }}) keeps only new or changed rows, and dbt merges them into the existing table on unique_key (MERGE, delete+insert, or partition overwrite depending on the strategy).
What goes wrong with incremental models, and how do you guard against it?
Without unique_key, changed rows are appended as duplicates. A batch holding two versions of a key makes MERGE fail or duplicate, so dedup the batch first. Late rows behind the high-water mark are missed, so add a lookback window. When the logic changes, the old rows are stale, so run a full refresh, and test the grain with unique on the key.
Incremental model or snapshot: what is the difference?
An incremental model keeps the current state of each row efficiently: a changed row replaces the old one. A snapshot keeps every version: it closes the old row with dbt_valid_to and inserts the new one, producing an SCD type 2 history. Use a snapshot when you need to know what a value was at a point in time.
Your incremental model on BigQuery costs as much per run as rebuilding the table. Why, and what do you change?
The default merge joins the batch to the destination on unique_key and, with nothing to narrow it, scans the whole destination, so a 5 GB batch costs a 2 TB scan. I would partition the table by event date, cluster by the key, and either add incremental_predicates that limit the destination to the recent days a batch can touch, or switch to insert_overwrite so dbt replaces only the partitions present in the batch. Then I would check the bytes processed per run before and after.