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 4 of 6 · Lab · 25 min · revision 2

Snapshots, Macros and Keeping Jinja in Check

A DuckDB lab: record Type 2 history of a customer table that is updated in place with a timestamp snapshot and a check snapshot, run them over three days of changes, query the history as of a point in time, then write a reusable macro, find a Jinja bug in compiled SQL and rewrite an over-templated model as plain SQL.

Contentsand lesson path

What you will learn

  • Capture Type 2 history with snapshots and reuse logic with macros and Jinja while keeping compiled SQL readable.

Prerequisites: SQL Fundamentals

01. Goal and setup

A CRM (customer relationship management) system keeps one row per customer and overwrites it when the plan, status or email changes. The old values are gone, so nobody can answer "which plan was this customer on last Tuesday?". In the first half of this lab you fix that with snapshots, dbt's way to record Type 2 history: one row per version, each with the time range in which it was valid. Type 2 history and point-in-time joins are explained in the dimensional modelling lab; here dbt maintains the history for you. In the second half you write a macro and learn to read compiled SQL.

The lab was tested with dbt Core 1.12.7, dbt-duckdb 1.11.1 and DuckDB 1.5.6. Snapshots are configured in YAML, as dbt has supported since version 1.9. Older projects define them in .sql files with a {% snapshot %} block; that legacy style still runs, but new snapshots should use YAML.

Terminal
mkdir crm && cd crm
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 snapshots macros

02. Step 1: Create the project and day 1 of the CRM

The loader applies one day of changes at a time, the way the CRM would. Day 1 creates three customers and the billing tables used later. Day 2 changes a plan, changes an email and adds a customer. Day 3 cancels a customer and, because of a bug in the CRM, changes customer 1's plan without updating updated_at.

YAML · dbt_project.yml
name: crm
version: "1.0.0"
profile: crm
YAML · profiles.yml
crm:
  target: dev
  outputs:
    dev:
      type: duckdb
      path: crm.duckdb
      schema: dev
      threads: 1
Python · load_raw.py
"""Apply one day of in-place changes to the CRM's raw tables, as the CRM app would."""
import sys

import duckdb

DAY_1 = [
    "CREATE SCHEMA IF NOT EXISTS raw",
    """CREATE OR REPLACE TABLE raw.customers AS SELECT * FROM (VALUES
         (1, '[email protected]', 'free', 'active', '2026-06-01 09:00'::TIMESTAMP),
         (2, '[email protected]',  'pro',  'active', '2026-06-01 09:00'::TIMESTAMP),
         (3, '[email protected]',  'free', 'active', '2026-06-01 09:00'::TIMESTAMP)
       ) AS t(customer_id, email, plan, status, updated_at)""",
    """CREATE OR REPLACE TABLE raw.invoices AS SELECT * FROM (VALUES
         (501, 1, 1250, 250), (502, 2, 9900, 1980), (503, 3, 4999, 1000)
       ) AS t(invoice_id, customer_id, net_cents, tax_cents)""",
    """CREATE OR REPLACE TABLE raw.refunds AS SELECT * FROM (VALUES
         (71, 502, 4950)) AS t(refund_id, invoice_id, refund_cents)""",
]
DAY_2 = [
    "UPDATE raw.customers SET plan = 'team', updated_at = '2026-06-02 10:00'"
    " WHERE customer_id = 2",
    "UPDATE raw.customers SET email = '[email protected]',"
    " updated_at = '2026-06-02 11:00' WHERE customer_id = 3",
    "INSERT INTO raw.customers VALUES"
    " (4, '[email protected]', 'pro', 'active', '2026-06-02 12:00')",
]
DAY_3 = [
    "UPDATE raw.customers SET status = 'cancelled',"
    " updated_at = '2026-06-03 08:00' WHERE customer_id = 2",
    # a bug in the CRM: this change does not touch updated_at
    "UPDATE raw.customers SET plan = 'pro' WHERE customer_id = 1",
]

day = int(sys.argv[1])
con = duckdb.connect("crm.duckdb")
for statement in {1: DAY_1, 2: DAY_2, 3: DAY_3}[day]:
    con.execute(statement)
print(f"day {day} applied; raw.customers now holds:")
for row in con.execute("SELECT * FROM raw.customers ORDER BY 1").fetchall():
    print(*row)
YAML · models/staging/_sources.yml
sources:
  - name: crm
    schema: raw
    tables:
      - name: customers
        columns:
          - name: customer_id
            data_tests: [unique, not_null]
      - name: invoices
      - name: refunds
Terminal
python load_raw.py 1
Expected output
day 1 applied; raw.customers now holds:
1 [email protected] free active 2026-06-01 09:00:00
2 [email protected] pro active 2026-06-01 09:00:00
3 [email protected] free active 2026-06-01 09:00:00

03. Step 2: Declare two snapshots

A snapshot has a relation to copy (a source or a model), a unique_key that identifies one record, and a strategy that decides when a record has changed:

  • timestamp compares the updated_at column with the value stored for the current version. dbt recommends it when the source keeps that column reliable.
  • check compares the columns listed in check_cols with the stored version. It needs no timestamp, but it sees only the columns you list.

The file declares one snapshot of each kind on the same source so that you can compare them. schema: snapshots puts them in their own schema; dbt combines it with the target schema into dev_snapshots. A separate schema signals that these tables are special: a snapshot cannot be rebuilt from its source, because the old versions exist nowhere else. For the same reason, dbt ignores --full-refresh for snapshots. dbt_valid_to_current stores a far-future date instead of NULL in the current version, which makes date-range queries simpler.

YAML · snapshots/customers_snapshots.yml
snapshots:
  - name: customers_history
    relation: source('crm', 'customers')
    config:
      schema: snapshots
      unique_key: customer_id
      strategy: timestamp
      updated_at: updated_at
      dbt_valid_to_current: "'9999-12-31'::timestamp"

  - name: customer_plan_history
    relation: source('crm', 'customers')
    config:
      schema: snapshots
      unique_key: customer_id
      strategy: check
      check_cols: [plan, status]

dbt adds meta-columns to every snapshot row. dbt_valid_from and dbt_valid_to bound the period in which a version was true. The script below prints both snapshots. For the check snapshot it shows only whether a version is current: without updated_at, its times are the clock time of each run and differ on every machine.

Python · history.py
"""Print the versions held by both snapshots, oldest first per customer."""
import duckdb

con = duckdb.connect("crm.duckdb", read_only=True)

print("customers_history (timestamp strategy)")
for row in con.execute("""
    select customer_id, plan, status, email,
           strftime(dbt_valid_from, '%Y-%m-%d %H:%M'),
           strftime(dbt_valid_to, '%Y-%m-%d %H:%M')
    from dev_snapshots.customers_history
    order by customer_id, dbt_valid_from""").fetchall():
    print(*row)

# check strategy: valid_from is the time of the snapshot run, so it is not printed
print("customer_plan_history (check strategy)")
for row in con.execute("""
    select customer_id, plan, status,
           case when dbt_valid_to is null then 'current' else 'closed' end
    from dev_snapshots.customer_plan_history
    order by customer_id, dbt_valid_from""").fetchall():
    print(*row)

04. Step 3: Snapshot day 1 and day 2

dbt snapshot runs every snapshot. The first run creates each table from the current source rows; later runs compare and add versions. Run it on day 1, apply day 2, and run it again.

Terminal
dbt snapshot --quiet
python load_raw.py 2 > /dev/null
dbt snapshot --quiet
python history.py
Expected output
customers_history (timestamp strategy)
1 free active [email protected] 2026-06-01 09:00 9999-12-31 00:00
2 pro active [email protected] 2026-06-01 09:00 2026-06-02 10:00
2 team active [email protected] 2026-06-02 10:00 9999-12-31 00:00
3 free active [email protected] 2026-06-01 09:00 2026-06-02 11:00
3 free active [email protected] 2026-06-02 11:00 9999-12-31 00:00
4 pro active [email protected] 2026-06-02 12:00 9999-12-31 00:00
customer_plan_history (check strategy)
1 free active current
2 pro active closed
2 team active current
3 free active current
4 pro active current

Read customer 2 in the timestamp snapshot: the pro version is valid from 1 June 09:00 until 2 June 10:00, and the team version from then on. dbt closed the old version with the new row's updated_at, so the two ranges meet without a gap or an overlap. Customer 3's email change also produced a version there. The check snapshot ignored it, because email is not in check_cols.

05. Step 4: Day 3 and a change without a timestamp

Terminal
python load_raw.py 3 > /dev/null
dbt snapshot --quiet
python history.py
Expected output
customers_history (timestamp strategy)
1 free active [email protected] 2026-06-01 09:00 9999-12-31 00:00
2 pro active [email protected] 2026-06-01 09:00 2026-06-02 10:00
2 team active [email protected] 2026-06-02 10:00 2026-06-03 08:00
2 team cancelled [email protected] 2026-06-03 08:00 9999-12-31 00:00
3 free active [email protected] 2026-06-01 09:00 2026-06-02 11:00
3 free active [email protected] 2026-06-02 11:00 9999-12-31 00:00
4 pro active [email protected] 2026-06-02 12:00 9999-12-31 00:00
customer_plan_history (check strategy)
1 free active closed
1 pro active current
2 pro active closed
2 team active closed
2 team cancelled current
3 free active current
4 pro active current

Customer 1 is on pro in the source, but the timestamp snapshot still says free: updated_at did not move, so to that strategy nothing changed. The check snapshot compared plan itself and caught it. Each strategy has a cost. Timestamp trusts the source to keep updated_at honest. Check sees only its listed columns, and its times are when the snapshot ran, possibly hours after the change. Both see only the state at each run, so two changes between runs leave one version. Schedule snapshots at least as often as the history you need.

06. Step 5: Ask what was true at a point in time

Downstream models read a snapshot with ref(), like any model. An "as of" query keeps the version whose range contains the moment you ask about: valid from at or before it, and valid to after it. The far-future dbt_valid_to of current rows makes that a plain comparison. The moment comes from var(), which reads a project variable you can pass on the command line. The default, a date far in the future, returns the current version of every customer.

SQL · models/customers_as_of.sql
-- the version of each customer that was valid at one moment
{% set as_of = var('as_of', '2999-01-01 00:00') %}
select customer_id, plan, status, email
from {{ ref('customers_history') }}
where dbt_valid_from <= timestamp '{{ as_of }}'
  and dbt_valid_to > timestamp '{{ as_of }}'
order by customer_id
Terminal
dbt show --select customers_as_of --vars '{as_of: "2026-06-02 10:30"}' --quiet
dbt show --select customers_as_of --quiet
Expected output
| customer_id | plan | status | email           |
| ----------- | ---- | ------ | --------------- |
|           1 | free | active | [email protected] |
|           2 | team | active | [email protected]  |
|           3 | free | active | [email protected]  |

| customer_id | plan | status    | email           |
| ----------- | ---- | --------- | --------------- |
|           1 | free | active    | [email protected] |
|           2 | team | cancelled | [email protected]  |
|           3 | free | active    | [email protected]  |
|           4 | pro  | active    | [email protected]  |

At 10:30 on 2 June, customer 2 had just moved to team, customer 3 still had the old email, and customer 4 did not exist yet. The second query shows today's state. Customer 1 is still free here, because this model reads the timestamp snapshot that missed the change.

07. Step 6: A macro that earns its place

A macro is a reusable piece of Jinja that returns SQL text, written in a .sql file under macros/. The billing tables store money in cents in three columns across two tables, and each must become a decimal amount the same way. That is a good reason for a macro: one definition, used several times, with a name that says what it does. If the rule changes, you change one file.

SQL · macros/cents_to_amount.sql
{% macro cents_to_amount(column_name, scale=2) -%}
    cast({{ column_name }} / 100 as decimal(12, {{ scale }}))
{%- endmacro %}
SQL · models/staging/stg_invoices.sql
select
    invoice_id,
    customer_id,
    {{ cents_to_amount('net_cents') }} as net_amount,
    {{ cents_to_amount('tax_cents') }} as tax_amount
from {{ source('crm', 'invoices') }}
SQL · models/staging/stg_refunds.sql
select
    refund_id,
    invoice_id,
    {{ cents_to_amount('refund_cents') }} as refund_amount
from {{ source('crm', 'refunds') }}

The - inside {%- and -%} is whitespace control: it removes the spaces and line breaks next to the tag, so the macro returns one clean line. Compile one model and read what the database will receive.

Terminal
dbt compile --select stg_invoices --quiet
dbt show --select stg_invoices --quiet
Expected output
select
    invoice_id,
    customer_id,
    cast(net_cents / 100 as decimal(12, 2)) as net_amount,
    cast(tax_cents / 100 as decimal(12, 2)) as tax_amount
from "crm"."raw"."invoices"
| invoice_id | customer_id | net_amount | tax_amount |
| ---------- | ----------- | ---------- | ---------- |
|        501 |           1 |      12.50 |        2.5 |
|        502 |           2 |      99.00 |       19.8 |
|        503 |           3 |      49.99 |       10.0 |

The compiled SQL reads like SQL a person would write. That is the test for any macro: if a reviewer cannot predict the compiled output from the call, the macro hides too much. (dbt show prints each column with only as many decimals as its values need, so tax_amount shows one; the stored type still has two.)

08. Step 7: Find a Jinja bug in the compiled SQL

Some Jinja mistakes compile without complaint and only fail in the database, with a line number that points into SQL you never wrote. Make a typical mistake on purpose: remove the quotes around the macro argument in stg_refunds.sql, so the call reads {{ cents_to_amount(refund_cents) }}.

Terminal
sed -i.bak "s/cents_to_amount('refund_cents')/cents_to_amount(refund_cents)/" \
  models/staging/stg_refunds.sql
dbt compile --select stg_refunds --quiet
Expected output
select
    refund_id,
    invoice_id,
    cast( / 100 as decimal(12, 2)) as refund_amount
from "crm"."raw"."refunds"

Without quotes, refund_cents is the name of a Jinja variable, not a string. No such variable exists, and dbt renders an undefined variable here as empty text, so the column vanished and compilation still succeeded. dbt run would fail with Parser Error: syntax error at or near "/". Reading the compiled SQL shows the cause at once. Put the quotes back with mv models/staging/stg_refunds.sql.bak models/staging/stg_refunds.sql.

09. Step 8: When Jinja goes too far

Templates invite cleverness. Here is the same invoice model written by someone who wanted no repeated words. It builds column names from fragments in two loops.

SQL · models/staging/stg_invoices_clever.sql
{% set id_columns = ['invoice', 'customer'] %}
{% set money_columns = ['net', 'tax'] %}
select
{% for c in id_columns %}
    {{ c ~ '_id' }},
{% endfor %}
{% for c in money_columns %}
    {{ cents_to_amount(c ~ '_cents') }} as {{ c }}_amount
    {%- if not loop.last %},{% endif %}
{% endfor %}
from {{ source('crm', 'invoices') }}
Terminal
dbt compile --select stg_invoices_clever --quiet
Expected output
select

    invoice_id,

    customer_id,


    cast(net_cents / 100 as decimal(12, 2)) as net_amount,

    cast(tax_cents / 100 as decimal(12, 2)) as tax_amount

from "crm"."raw"."invoices"

The result is the same query with stray blank lines, but the source has grown from six lines to eleven, and no column name appears whole in it. A search for net_amount finds nothing, and a reviewer must run the loops in their head. Delete the file with rm models/staging/stg_invoices_clever.sql.

A few rules keep Jinja in check:

  • Write plain SQL first. Reach for a macro when the same logic appears in several models, not to shorten one file.
  • Loops pay off for long or changing lists, such as a pivot over twenty payment methods; use whitespace control in them.
  • Keep identifiers whole in the source, so a search finds them.
  • Read target/compiled/ (or dbt compile) before you open a pull request, and expect reviewers to read it too.
  • Give a project variable a sensible default, so that a run without --vars still compiles.

10. Check your understanding

Practice check · 3 questions

History, as-of queries and compiled SQL

Each question uses the snapshots and models of this lab.

Q1. Customer 3 changed only their email on day 2. How many rows does customer 3 have in `customer_plan_history` (check strategy, `check_cols: [plan, status]`) after day 3?
Q2. You remove `dbt_valid_to_current` from a new snapshot, so current versions have `dbt_valid_to` NULL. What does the as-of filter `dbt_valid_from <= t and dbt_valid_to > t` now return?
Q3. A model calls `{{ cents_to_amount(net_cents) }}` without quotes, and no Jinja variable called `net_cents` exists. What does `dbt compile` do?
Practice only: not graded, not saved, not evidence.

11. Apply it

The practice project needs an SCD Type 2 snapshot of customers. Build it for your own data:

  1. Decide whether you trust your customers source's updated_at. Change a row without touching it, as day 3 did, and see which strategy notices.
  2. Put the snapshot in its own schema, add unique and not_null tests on the source key, and schedule dbt snapshot before the models that read it.
  3. Write a dim_customers_history model on top of the snapshot and join an orders fact to it on order_date between dbt_valid_from and dbt_valid_to.
  4. Find one piece of repeated logic in your staging models and turn it into a macro; read the compiled SQL before and after.

12. Review prompt

Without looking back, explain in your own words:

  • how the timestamp and check strategies decide that a record changed, and what each one missed in this lab;
  • what dbt_valid_from and dbt_valid_to mean, and why a snapshot cannot be rebuilt with --full-refresh;
  • how to query the state of a customer at a past moment;
  • when a macro is worth writing, and how compiled SQL helps you review one.

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