Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 25 min · revision 2

Materializations and Incremental Models

A worked example on DuckDB: choose view, table, incremental or ephemeral for each model of an events pipeline, then run an incremental fact model over two daily deliveries that include late and corrected events, and compare it with a no-lookback and a no-key version before repairing both with --full-refresh.

Contentsand lesson path

What you will learn

  • Choose view, table, incremental or ephemeral materializations and implement an incremental model with a unique key and a late-data lookback.

Prerequisites: SQL Fundamentals

01. The problem

A mobile app sends usage events (views and purchases) to the warehouse once a day. Phones go offline, so an event can arrive up to two days after the day it happened. Sometimes the app re-sends an event with a corrected amount; the copy has the same event_id. Analysts want fct_events, one row per event with the latest amount, and finance reads revenue from it every morning.

At full size this table grows by millions of rows a day, and a nightly rebuild would re-read years of history to add one day. In this worked example you decide how each model of the pipeline should be stored, then build fct_events so that each daily run processes only recent data and still ends with the right answer. The project uses the same versions as the lab before: dbt Core 1.12.7, dbt-duckdb 1.11.1 and DuckDB 1.5.6.

Terminal
mkdir events && cd events
python3 -m venv .venv && source .venv/bin/activate
pip install "dbt-core==1.12.7" "dbt-duckdb==1.11.1" "duckdb==1.5.6"
mkdir -p models/staging models/intermediate models/marts

The loader below plays the ingestion job. python load_events.py 1 appends the delivery of 3 May, and python load_events.py 2 appends the delivery of 4 May, which holds two new events, two late ones and a corrected copy of event 5. loaded_at records when each row arrived.

Python · load_events.py
"""Append one delivery of app events to raw.events, as an ingestion job would."""
import sys

import duckdb

BATCHES = {
    1: [  # delivered on 3 May
        (1, "u1", "view", "2026-04-29", 0),
        (2, "u2", "view", "2026-04-30", 0),
        (3, "u1", "buy", "2026-05-01", 1200),
        (4, "u3", "view", "2026-05-02", 0),
        (5, "u2", "buy", "2026-05-02", 800),
    ],
    2: [  # delivered on 4 May: new events, two late ones and a correction
        (6, "u1", "view", "2026-05-03", 0),
        (7, "u3", "buy", "2026-05-03", 450),
        (8, "u4", "view", "2026-05-01", 0),  # late
        (9, "u4", "buy", "2026-05-02", 300),  # late
        (5, "u2", "buy", "2026-05-02", 850),  # event 5 re-sent with the right amount
    ],
}
LOADED_AT = {1: "2026-05-03 06:00:00", 2: "2026-05-04 06:00:00"}

batch = int(sys.argv[1])
con = duckdb.connect("events.duckdb")
con.execute("CREATE SCHEMA IF NOT EXISTS raw")
con.execute(
    "CREATE TABLE IF NOT EXISTS raw.events (event_id INT, user_id TEXT, "
    "event_type TEXT, event_date DATE, amount_cents INT, loaded_at TIMESTAMP)"
)
rows = [row + (LOADED_AT[batch],) for row in BATCHES[batch]]
con.executemany("INSERT INTO raw.events VALUES (?, ?, ?, ?, ?, ?)", rows)
total = con.execute("SELECT count(*) FROM raw.events").fetchone()[0]
print(f"batch {batch}: loaded {len(rows)} rows, raw.events now has {total}")
Terminal
python load_events.py 1
Expected output
batch 1: loaded 5 rows, raw.events now has 5

02. Step 1: Choose a materialisation for each model

A materialisation decides two costs: the work each dbt run does, and the work each query against the model does. It also decides whether the model exists in the warehouse at all, and so whether anyone can query it.

  • view: dbt only stores the query. A build is almost free, but every query re-runs the SQL, so the data is always current and a heavy view is slow to read.
  • table: dbt re-runs the whole query and replaces the table on every build. Queries are fast, and the data is as fresh as the last build. Build cost grows with the full size of the input.
  • incremental: the first run builds a table; later runs process only the rows you filter for and merge or insert them. Builds stay small on large, mostly-append data, at the price of filter logic you must get right.
  • ephemeral: nothing is built. dbt pastes the model's SQL as a CTE (common table expression, a named sub-query in a with clause) into every model that refs it. Nobody can query it, and overuse makes compiled SQL long and hard to debug.

For this pipeline, stg_events only renames and converts, so it is a view. Deduplicating re-sent events is a small step used only by the fact model, so int_events_latest is ephemeral. fct_events is large, mostly append-only, and read every morning, so it is incremental. A small daily summary would be a plain table: cheap to rebuild and fast to query. Folder defaults go in dbt_project.yml; a model can override them in its own config().

YAML · dbt_project.yml
name: events
version: "1.0.0"
profile: events

models:
  events:
    staging:
      +materialized: view
    intermediate:
      +materialized: ephemeral
YAML · profiles.yml
events:
  target: dev
  outputs:
    dev:
      type: duckdb
      path: events.duckdb
      schema: dev
      threads: 1
YAML · models/staging/_sources.yml
sources:
  - name: app
    schema: raw
    tables:
      - name: events
SQL · models/staging/stg_events.sql
select
    event_id,
    user_id,
    event_type,
    event_date,
    amount_cents / 100.0 as amount,
    loaded_at
from {{ source('app', 'events') }}
SQL · models/intermediate/int_events_latest.sql
-- the app can re-send an event: keep the most recently loaded copy
select *
from {{ ref('stg_events') }}
qualify row_number() over (partition by event_id order by loaded_at desc) = 1

03. Step 2: Write the incremental model

An incremental model is a normal SELECT plus two decisions. The first is the filter: which rows should a later run read? is_incremental() returns true only when the target table already exists, the model is configured as incremental, and you did not pass --full-refresh. Inside that block, {{ this }} names the model's own existing table. The filter re-reads every event from two days before the latest date already loaded. That window is the lookback, and it matches the two days of lateness the app allows.

The second decision is unique_key: the column that identifies a row. With a key, dbt updates rows that already exist and inserts the rest, so re-reading the window cannot create duplicates and a corrected event replaces the old copy. incremental_strategy says how: dbt-duckdb supports append, delete+insert, merge and microbatch, and when you name none it uses delete+insert, which without a key simply inserts. merge needs DuckDB 1.4 or later.

SQL · models/marts/fct_events.sql
{{
    config(
        materialized='incremental',
        unique_key='event_id',
        incremental_strategy='merge'
    )
}}

select event_id, user_id, event_type, event_date, amount
from {{ ref('int_events_latest') }}
{% if is_incremental() %}
-- events arrive up to two days late: re-read a two-day window
where event_date >= (
    select max(event_date) - interval 2 day from {{ this }}
)
{% endif %}

To see why both decisions matter, build two flawed copies next to it. fct_events_naive has the key but no lookback: it reads only dates after the latest one loaded. fct_events_append has the lookback but no key, so dbt simply appends whatever the filter returns.

SQL · models/marts/fct_events_naive.sql
{{ config(materialized='incremental', unique_key='event_id') }}

select event_id, user_id, event_type, event_date, amount
from {{ ref('int_events_latest') }}
{% if is_incremental() %}
where event_date > (select max(event_date) from {{ this }})
{% endif %}
SQL · models/marts/fct_events_append.sql
{{ config(materialized='incremental') }}

select event_id, user_id, event_type, event_date, amount
from {{ ref('int_events_latest') }}
{% if is_incremental() %}
where event_date >= (
    select max(event_date) - interval 2 day from {{ this }}
)
{% endif %}

compare.py computes the truth straight from raw.events, keeping the latest copy of each event, and prints row counts, distinct event ids and purchase revenue for it and for each model.

Python · compare.py
"""Compare each incremental model with the truth computed from raw.events."""
import duckdb

con = duckdb.connect("events.duckdb", read_only=True)
truth = """(select * from raw.events
            qualify row_number() over (partition by event_id
                                       order by loaded_at desc) = 1)"""
print(f"{'relation':<22}{'rows':>5}{'ids':>5}{'revenue':>9}")
for name in ["truth", "fct_events_naive", "fct_events_append", "fct_events"]:
    rel = truth if name == "truth" else f"dev.{name}"
    amount = "amount_cents / 100.0" if name == "truth" else "amount"
    rows, ids, revenue = con.execute(
        f"select count(*), count(distinct event_id), sum({amount}) from {rel}"
    ).fetchone()
    print(f"{name:<22}{rows:>5}{ids:>5}{revenue:>9.2f}")

04. Step 3: Day 1, the first run builds everything

Terminal
dbt run --quiet
python compare.py
Expected output
relation               rows  ids  revenue
truth                     5    5    20.00
fct_events_naive          5    5    20.00
fct_events_append         5    5    20.00
fct_events                5    5    20.00

On the first run no table exists yet, so is_incremental() is false, the where clause is left out, and all three models read every row. They agree with the truth: 12.00 + 8.00 = 20.00. The difference only shows on the next delivery.

05. Step 4: Day 2, late and corrected events arrive

Load the second delivery and look at the SQL dbt will run for fct_events now that the table exists. dbt compile renders the Jinja, and the ephemeral model appears as a CTE named __dbt__cte__int_events_latest.

Terminal
python load_events.py 2
dbt compile --select fct_events --quiet
Expected output
batch 2: loaded 5 rows, raw.events now has 10


with __dbt__cte__int_events_latest as (
-- the app can re-send an event: keep the most recently loaded copy
select *
from "events"."dev"."stg_events"
qualify row_number() over (partition by event_id order by loaded_at desc) = 1
) select event_id, user_id, event_type, event_date, amount
from __dbt__cte__int_events_latest

-- events arrive up to two days late: re-read a two-day window
where event_date >= (
    select max(event_date) - interval 2 day from "events"."dev"."fct_events"
)

The latest date in the table is 2 May, so the window starts on 30 April. Event 1, from 29 April, is outside it; everything from 30 April on is read again. Now run all three models.

Terminal
dbt run --quiet
python compare.py
Expected output
relation               rows  ids  revenue
truth                     9    9    28.00
fct_events_naive          7    7    24.50
fct_events_append        13    9    48.00
fct_events                9    9    28.00

Check each line by hand. The truth is 12.00 + 8.50 + 4.50 + 3.00 = 28.00: event 5 now counts 8.50. fct_events matches it. The merge updated events 2 to 5, including the correction, and inserted events 6 to 9.

fct_events_naive read only events dated after 2 May, so it gained events 6 and 7. It lost the late events 8 and 9 and kept the old 8.00 for event 5. The next run will not repair this, because its filter never looks back. fct_events_append read the right window but had no key, so it inserted eight rows again on top of the five it had: four events now appear twice and purchase revenue is inflated. Neither failure raised an error.

06. Step 5: Repair with --full-refresh

--full-refresh makes is_incremental() return false for one run, so dbt rebuilds the table from all the input, as on day 1. Use it after you fix a filter, change the logic of old rows, or need a backfill. On a very large table that is expensive. Setting full_refresh: false in a model's config makes dbt ignore the flag for that model, which protects it from an accidental rebuild.

Terminal
dbt run --select fct_events_naive fct_events_append --full-refresh --quiet
python compare.py
Expected output
relation               rows  ids  revenue
truth                     9    9    28.00
fct_events_naive          9    9    28.00
fct_events_append         9    9    28.00
fct_events                9    9    28.00

Both are correct again, but only until the next late event: a full refresh hides the flaw without fixing it. In a real project you would now delete the two flawed models.

07. Step 6: Add a column to the incremental model

Analysts ask for loaded_at in fct_events. Add it to the select line, so that it reads select event_id, user_id, event_type, event_date, amount, loaded_at, and run only that model.

Terminal
sed -i.bak "s/event_date, amount$/event_date, amount, loaded_at/" \
  models/marts/fct_events.sql
dbt run --select fct_events --quiet
Illustrative output
23:41:30  [ERROR]: in model fct_events (models/marts/fct_events.sql)
23:41:30    Runtime Error in model fct_events (models/marts/fct_events.sql)
  Binder Error: Table "fct_events" does not have a column with name "loaded_at"

The existing table has no loaded_at column, and the merge matches columns by name, so it fails. The on_schema_change config controls what dbt does when the columns change; its default, ignore, leaves the table as it is. append_new_columns adds new columns. Add it to the config block, after the strategy:

SQL · models/marts/fct_events.sql
{{
    config(
        materialized='incremental',
        unique_key='event_id',
        incremental_strategy='merge',
        on_schema_change='append_new_columns'
    )
}}

select event_id, user_id, event_type, event_date, amount, loaded_at
from {{ ref('int_events_latest') }}
{% if is_incremental() %}
-- events arrive up to two days late: re-read a two-day window
where event_date >= (
    select max(event_date) - interval 2 day from {{ this }}
)
{% endif %}
Terminal
dbt run --select fct_events --quiet
dbt show --inline "select event_id, event_date, loaded_at
  from {{ ref('fct_events') }} order by 1" --limit 10 --quiet
Expected output
| event_id | event_date |           loaded_at |
| -------- | ---------- | ------------------- |
|        1 | 2026-04-29 |                     |
|        2 | 2026-04-30 |                     |
|        3 | 2026-05-01 | 2026-05-03 06:00:00 |
|        4 | 2026-05-02 | 2026-05-03 06:00:00 |
|        5 | 2026-05-02 | 2026-05-04 06:00:00 |
|        6 | 2026-05-03 | 2026-05-04 06:00:00 |
|        7 | 2026-05-03 | 2026-05-04 06:00:00 |
|        8 | 2026-05-01 | 2026-05-04 06:00:00 |
|        9 | 2026-05-02 | 2026-05-04 06:00:00 |

The column exists, but events 1 and 2 have no value. The latest date is now 3 May, so this run re-read only events from 1 May onwards; older rows were never touched. A new column needs a backfill; here a full refresh is the simplest one. Run dbt run --select fct_events --full-refresh --quiet and repeat the dbt show: every row now has its loaded_at.

08. Check your understanding

Practice check · 3 questions

Reading the results of the events pipeline

Each question refers to the models and the output of this worked example.

Q1. After day 2, `fct_events_append` holds 13 rows for 9 distinct events. What produced the extra four rows?
Q2. You change `int_events_latest` from ephemeral to view and run `dbt run`. What changes in the compiled SQL of `fct_events`?
Q3. In step 6, `append_new_columns` added `loaded_at`, but some rows stayed NULL. Which rows, and why?
Practice only: not graded, not saved, not evidence.

09. Apply it

The practice project needs one incremental fact model. Apply the method to your orders data:

  1. Measure how late your orders arrive: compare the order date with the load time in the raw table and choose a lookback that covers almost all of it.
  2. Write the model with unique_key, a lookback and an explicit strategy, plus a unique and a not_null test on the key.
  3. Load two batches with a late row and a correction, as load_events.py does, and prove with a comparison script that the model equals a full rebuild.
  4. Add a daily_revenue table on top and explain why it does not need to be incremental.

10. Review prompt

Without looking back, explain in your own words:

  • the build cost, query cost and visibility of view, table, incremental and ephemeral models;
  • the three conditions under which is_incremental() is true, and what {{ this }} points to;
  • what the lookback and the unique_key each protect against, using the numbers from step 4;
  • when you need --full-refresh, and what on_schema_change does and does not do.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check