dbt Interview Questions and Answers Part 5 - Snapshots and SCD Type 2

dbt Interview Q&A · Part 5 of 10

In this post we are going to cover dbt snapshots and SCD Type 2: the timestamp and check strategies, hard deletes, point-in-time joins, the NULL in dbt_valid_to, and the best practices that protect your history. These are 7 real dbt interview questions for data engineers, asked the way they come up on a real project, and the last one is a scenario where the source system was down for a week and then sent all the changes at once.

Most source systems only keep the current value of a row. When a customer moves, the old city is overwritten and gone. A snapshot is how dbt keeps that history: every run compares the source with what it saw last time and records each change as a new version, which is SCD Type 2. Interviewers ask about snapshots because the history can't be rebuilt later, so the design choices you make on day one really matter.

Part 5 of the Real Time dbt Interview Questions and Answers series on TechBrothersIT.

The short answer

Say this first

A snapshot turns a source that overwrites rows into SCD Type 2 history: each run closes changed rows with dbt_valid_to and inserts the new version. Prefer the timestamp strategy, decide hard_deletes and dbt_valid_to_current on day one, join facts with a point-in-time range, and test the unique key first: a snapshot only records what it sees when it runs.

Let's create the project and some sample data

Our project has a seed called customers that stands in for the app database, with three customers: Ali in Dallas, Sara in Austin and John in Houston. The sources file declares it as app_db.customers, with key tests. There are two snapshots on it: customers_snapshot with the timestamp strategy, and customers_check_snapshot with the check strategy. Here are the starting files. The full script at the end also writes a profiles.yml that points at a local DuckDB file.

dbt_project.yml
name: shop
version: '1.0'
profile: shop
seeds/customers.csv
customer_id,name,city,updated_at
1,Ali,Dallas,2025-03-01 09:00:00
2,Sara,Austin,2025-04-10 14:30:00
3,John,Houston,2025-05-20 11:15:00
models/sources.yml
sources:
  - name: app_db
    schema: main  # in this demo, dbt seed loads the app tables here
    tables:
      - name: customers
        columns:
          - name: customer_id
            data_tests:
              - unique
              - not_null
      - name: orders
snapshots/customers_snapshot.yml
snapshots:
  - name: customers_snapshot
    relation: source('app_db', 'customers')
    config:
      schema: snapshots
      strategy: timestamp
      unique_key: customer_id
      updated_at: updated_at
      hard_deletes: new_record
snapshots/customers_check_snapshot.yml
snapshots:
  - name: customers_check_snapshot
    relation: source('app_db', 'customers')
    config:
      schema: snapshots
      strategy: check
      unique_key: customer_id
      check_cols: [city]

Question 1: The business wants to see a customer's address as it was last year, but the source only keeps the current value. How do snapshots help?

A snapshot is dbt's built-in SCD Type 2. You point it at the source table, give it a unique key, and pick how to detect a change. Ours uses the timestamp strategy on updated_at, in its own snapshots schema.

Let's run dbt seed, then dbt snapshot.

Terminal
$ dbt seed
 Succeeded seed  main.customers (table)

Finished 'seed' successfully for target 'dev'
Processed: 1 seed
Summary: 1 total | 1 success
$ dbt snapshot
 Succeeded snapshot main_snapshots.customers_check_snapshot (snapshot)
 Succeeded snapshot main_snapshots.customers_snapshot (snapshot)

Finished 'snapshot' successfully for target 'dev'
Processed: 2 snapshots
Summary: 2 total | 2 success
SQL - check the table (DuckDB)
select customer_id, name, city, dbt_valid_from, dbt_valid_to
from main_snapshots.customers_snapshot
order by customer_id, dbt_valid_from
Result3 rows
customer_idnamecitydbt_valid_fromdbt_valid_to
1AliDallas2025-03-01 09:00NULL
2SaraAustin2025-04-10 14:30NULL
3JohnHouston2025-05-20 11:15NULL

The first run copies every row and adds dbt_valid_from and dbt_valid_to. For the current version, dbt_valid_to is NULL. Now Ali moves from Dallas to Denver, and the source overwrites the city. We seed and snapshot again.

seeds/customers.csv
customer_id,name,city,updated_at
1,Ali,Denver,2026-02-15 10:00:00
2,Sara,Austin,2025-04-10 14:30:00
3,John,Houston,2025-05-20 11:15:00
Terminal
$ dbt seed
 Succeeded seed  main.customers (table)

Finished 'seed' successfully for target 'dev'
Processed: 1 seed
Summary: 1 total | 1 success
$ dbt snapshot
 Succeeded snapshot main_snapshots.customers_check_snapshot (snapshot)
 Succeeded snapshot main_snapshots.customers_snapshot (snapshot)

Finished 'snapshot' successfully for target 'dev'
Processed: 2 snapshots
Summary: 2 total | 2 success
SQL - check the table (DuckDB)
select customer_id, name, city, dbt_valid_from, dbt_valid_to
from main_snapshots.customers_snapshot
order by customer_id, dbt_valid_from
Result4 rows
customer_idnamecitydbt_valid_fromdbt_valid_to
1AliDallas2025-03-01 09:002026-02-15 10:00
1AliDenver2026-02-15 10:00NULL
2SaraAustin2025-04-10 14:30NULL
3JohnHouston2025-05-20 11:15NULL

The Dallas row is closed at 2026-02-15 10:00, the new updated_at, and the Denver row is now current. Ali has two versions.

To see last year, we filter on the validity range: dbt_valid_from on or before the date, and dbt_valid_to after it or NULL, skipping the deleted markers. Let's look at December 31, 2025 with dbt show.

models/customers_as_of.sql
{% set as_of = "timestamp '2025-12-31'" %}

select customer_id, name, city
from {{ ref('customers_snapshot') }}
where dbt_valid_from <= {{ as_of }}
  and (dbt_valid_to > {{ as_of }} or dbt_valid_to is null)
  and dbt_is_deleted = 'False'
Terminal
$ dbt show -s customers_as_of
Query show_model_shop_customers_as_of
┌─────────────┬──────┬─────────┐
│ customer_id ┆ name ┆ city    │
╞═════════════╪══════╪═════════╡
│ 1           ┆ Ali  ┆ Dallas  │
│ 2           ┆ Sara ┆ Austin  │
│ 3           ┆ John ┆ Houston │
└─────────────┴──────┴─────────┘
3 rows.
 Succeeded model main.customers_as_of (view)

Finished 'show' successfully for target 'dev'

On that date Ali was still in Dallas, Sara in Austin and John in Houston.

The catch

A snapshot only records what it sees when it runs. It can't rebuild history it never saw, so start it early and run it after each load.

Question 2: A teammate asks when to use the timestamp strategy and when to use the check strategy. What do you say?

Timestamp is the first choice, and the one the docs recommend. Check is for sources with no reliable updated_at.

Let's put the two side by side.

timestamp (recommended)check
DETECTS A CHANGEupdated_at is newera check_cols value differs
DBT_VALID_FROMthe source updated_atthe snapshot run time
USE WHENevery change bumps updated_atno reliable updated_at

Timestamp compares one column, updated_at, so it's cheap, and dbt_valid_from is the real change time from the source. Check compares the columns you list in check_cols, here the city, and dbt_valid_from is the time the snapshot ran.

Now here is the trap with timestamp. The app changes Sara's city to San Antonio, but doesn't touch updated_at. We seed and run both snapshots, then compare Sara's versions.

seeds/customers.csv
customer_id,name,city,updated_at
1,Ali,Denver,2026-02-15 10:00:00
2,Sara,San Antonio,2025-04-10 14:30:00
3,John,Houston,2025-05-20 11:15:00
Terminal
$ dbt seed
 Succeeded seed  main.customers (table)

Finished 'seed' successfully for target 'dev'
Processed: 1 seed
Summary: 1 total | 1 success
$ dbt snapshot
 Succeeded snapshot main_snapshots.customers_check_snapshot (snapshot)
 Succeeded snapshot main_snapshots.customers_snapshot (snapshot)

Finished 'snapshot' successfully for target 'dev'
Processed: 2 snapshots
Summary: 2 total | 2 success
SQL - check the table (DuckDB)
with versions as (
  select 'customers_snapshot' as snapshot, city, dbt_valid_to is null as is_current
  from main_snapshots.customers_snapshot where customer_id = 2
  union all
  select 'customers_check_snapshot', city, dbt_valid_to is null
  from main_snapshots.customers_check_snapshot where customer_id = 2
)
select * from versions order by snapshot desc, is_current
Result3 rows
snapshotcityis_current
customers_snapshotAustintrue
customers_check_snapshotAustinfalse
customers_check_snapshotSan Antoniotrue

The timestamp snapshot still has one version for Sara: Austin, still current. The check snapshot closed Austin and recorded San Antonio as current.

So the strategy is a question about your source:

  • updated_at is bumped on every change: use timestamp
  • You can't trust it: use check, with an explicit column list or one hash column
  • Avoid check_cols: all: one new source column versions every row

With check, you can still set updated_at. Then dbt_valid_from comes from that column instead of the run time.

Question 3: Records deleted in the source still look current in the snapshot. How do you handle hard deletes?

Set the hard_deletes config. By default it is ignore: when a row disappears from the source, the snapshot does nothing, so the last version stays current forever.

There are two other settings.

hard_deleteswhen a row disappears from the source
ignore (default)nothing: the last version stays current
invalidatecloses the last version: sets dbt_valid_to
new_recordcloses it, and inserts a row with dbt_is_deleted = 'True'

Our main snapshot uses new_record, and the check snapshot is on the default. Now John is deleted in the app. Let's seed and run the snapshots.

seeds/customers.csv
customer_id,name,city,updated_at
1,Ali,Denver,2026-02-15 10:00:00
2,Sara,San Antonio,2025-04-10 14:30:00
Terminal
$ dbt seed
 Succeeded seed  main.customers (table)

Finished 'seed' successfully for target 'dev'
Processed: 1 seed
Summary: 1 total | 1 success
$ dbt snapshot
 Succeeded snapshot main_snapshots.customers_check_snapshot (snapshot)
 Succeeded snapshot main_snapshots.customers_snapshot (snapshot)

Finished 'snapshot' successfully for target 'dev'
Processed: 2 snapshots
Summary: 2 total | 2 success
SQL - check the table (DuckDB)
with versions as (
  select 'customers_check_snapshot' as snapshot, city, null as dbt_is_deleted, dbt_valid_to is null as is_current
  from main_snapshots.customers_check_snapshot where customer_id = 3
  union all
  select 'customers_snapshot', city, dbt_is_deleted, dbt_valid_to is null
  from main_snapshots.customers_snapshot where customer_id = 3
)
select * from versions order by snapshot, is_current
Result3 rows
snapshotcitydbt_is_deletedis_current
customers_check_snapshotHoustonNULLtrue
customers_snapshotHoustonFalsefalse
customers_snapshotHoustonTruetrue

The check snapshot still shows Houston as current. The main snapshot closed John's row, and added a current row with dbt_is_deleted set to True.

Two more details. The source has no delete time, so dbt uses the snapshot run time for that change. And if the record comes back, dbt inserts a new version with dbt_is_deleted set to False.

Two tips from real projects:

  • Decide this when you create the snapshot. dbt doesn't migrate an existing table when you switch.
  • Use it only when the source holds every row. A partial load marks the missing rows deleted.

Question 4: A report joins facts to the snapshot and gets duplicate rows. How do you join to an SCD Type 2 table correctly?

With a point-in-time join: match the key, and the fact's time inside the validity range. The snapshot has one row per version, not one row per customer, so a join on the key alone fans out.

Let's see it. We add three orders and a fct_orders model that joins the snapshot on customer_id only.

seeds/orders.csv
order_id,customer_id,amount,ordered_at
101,1,120.00,2025-11-05 12:00:00
102,1,80.00,2026-03-01 09:30:00
103,2,45.00,2025-12-01 16:45:00
models/fct_orders.sql
select o.order_id, o.customer_id, o.amount, o.ordered_at, c.city
from {{ source('app_db', 'orders') }} as o
left join {{ ref('customers_snapshot') }} as c
  on o.customer_id = c.customer_id
Terminal
$ dbt seed -s orders
 Succeeded seed  main.orders (table)

Finished 'seed' successfully for target 'dev'
Processed: 1 seed
Summary: 1 total | 1 success
$ dbt run -s fct_orders
 Succeeded model main.fct_orders (view)

Finished 'run' successfully for target 'dev'
Processed: 1 model
Summary: 1 total | 1 success
SQL - check the table (DuckDB)
select order_id, customer_id, amount, ordered_at, city
from fct_orders
order by order_id, city
Result5 rows
order_idcustomer_idamountordered_atcity
10111202025-11-05 12:00Dallas
10111202025-11-05 12:00Denver
1021802026-03-01 09:30Dallas
1021802026-03-01 09:30Denver
1032452025-12-01 16:45Austin

Three orders became five rows. Ali has two versions, so his two orders, 101 and 102, each come back once with Dallas and once with Denver, and his revenue doubles.

Now the fix. The order time must be on or after dbt_valid_from, and before dbt_valid_to, or dbt_valid_to is NULL. Let's run the model again.

models/fct_orders.sql
select o.order_id, o.customer_id, o.amount, o.ordered_at, c.city
from {{ source('app_db', 'orders') }} as o
left join {{ ref('customers_snapshot') }} as c
  on o.customer_id = c.customer_id
 and o.ordered_at >= c.dbt_valid_from
 and (o.ordered_at < c.dbt_valid_to or c.dbt_valid_to is null)
Terminal
$ dbt run -s fct_orders
 Succeeded model main.fct_orders (view)

Finished 'run' successfully for target 'dev'
Processed: 1 model
Summary: 1 total | 1 success
SQL - check the table (DuckDB)
select order_id, customer_id, amount, ordered_at, city
from fct_orders
order by order_id, city
Result3 rows
order_idcustomer_idamountordered_atcity
10111202025-11-05 12:00Dallas
1021802026-03-01 09:30Denver
1032452025-12-01 16:45Austin

Three orders, three rows. Each order has the city where the customer lived when they ordered: Dallas for the November order, 101, and Denver for the March order, 102.

A few rules for this join:

  • Use >= for the start and strictly < for the end, so a boundary timestamp matches one version
  • Build the join once in the fact model, and store dbt_scd_id on the fact as the version key
  • For today's value, filter to current rows that aren't deleted

Question 5: The snapshot shows NULL in dbt_valid_to for current rows, and analysts keep writing IS NULL filters. What options do you have?

NULL means current, and that's the default. But NULL breaks between filters and range joins, and every analyst has to remember the or dbt_valid_to is null part. There are two options.

Option one is the dbt_valid_to_current config. Give it a SQL expression, here December 31, 9999, and dbt writes that instead of NULL for current rows. But watch what happens on an existing snapshot. We add the config, a new customer, Maria, arrives, and we snapshot.

snapshots/customers_snapshot.yml
snapshots:
  - name: customers_snapshot
    relation: source('app_db', 'customers')
    config:
      schema: snapshots
      strategy: timestamp
      unique_key: customer_id
      updated_at: updated_at
      hard_deletes: new_record
      dbt_valid_to_current: "cast('9999-12-31' as timestamp)"
seeds/customers.csv
customer_id,name,city,updated_at
1,Ali,Denver,2026-02-15 10:00:00
2,Sara,San Antonio,2025-04-10 14:30:00
4,Maria,El Paso,2026-06-01 08:00:00
Terminal
$ dbt seed -s customers
 Succeeded seed  main.customers (table)

Finished 'seed' successfully for target 'dev'
Processed: 1 seed
Summary: 1 total | 1 success
$ dbt snapshot
 Succeeded snapshot main_snapshots.customers_check_snapshot (snapshot)
 Succeeded snapshot main_snapshots.customers_snapshot (snapshot)

Finished 'snapshot' successfully for target 'dev'
Processed: 2 snapshots
Summary: 2 total | 2 success
SQL - check the table (DuckDB)
select customer_id, name, dbt_valid_to, dbt_is_deleted
from main_snapshots.customers_snapshot
where dbt_valid_to is null or dbt_valid_to = timestamp '9999-12-31'
order by customer_id
Result4 rows
customer_idnamedbt_valid_todbt_is_deleted
1AliNULLFalse
2SaraNULLFalse
3JohnNULLTrue
4Maria9999-12-31 00:00False

Maria's row gets 9999-12-31 00:00. The old current rows, Ali, Sara and John, keep NULL. dbt doesn't update them for you, so now you have both.

So we backfill once, with a small macro and dbt run-operation.

macros/backfill_valid_to.sql
{% macro backfill_valid_to() %}
  {% set sql %}
    update {{ ref('customers_snapshot') }}
    set dbt_valid_to = cast('9999-12-31' as timestamp)
    where dbt_valid_to is null
  {% endset %}
  {% do run_query(sql) %}
  {{ log('backfilled dbt_valid_to on the current rows', info=True) }}
{% endmacro %}
Terminal
$ dbt run-operation backfill_valid_to
backfilled dbt_valid_to on the current rows

Finished 'run-operation' successfully for target 'dev'
SQL - check the table (DuckDB)
select customer_id, name, dbt_valid_to, dbt_is_deleted
from main_snapshots.customers_snapshot
where dbt_valid_to is null or dbt_valid_to = timestamp '9999-12-31'
order by customer_id
Result4 rows
customer_idnamedbt_valid_todbt_is_deleted
1Ali9999-12-31 00:00False
2Sara9999-12-31 00:00False
3John9999-12-31 00:00True
4Maria9999-12-31 00:00False

The macro logs backfilled dbt_valid_to on the current rows, and now all four current rows end in 9999-12-31 00:00.

Option two works on any snapshot: a model on top with a coalesced valid_to and an is_current flag, so analysts never touch the meta columns.

Real project tip

Either way, decide on day one, before the snapshot has history.

Question 6: A snapshot was pointed at a messy source and now has wrong history. What are the best practices for snapshots?

The hard truth: snapshot history can't be rebuilt. Snapshots ignore --full-refresh, and the source no longer has the old values. So the rules are about protecting what goes in.

  • Snapshot the source as is: all columns, no joins, no business logic
  • Clean first? Do a light staging or ephemeral model, like a dedup, and snapshot that. Business logic goes downstream.
  • Test the unique key before the snapshot runs
  • Own schema: tighter permissions and backups
  • Timestamp strategy, with hard_deletes chosen on day one
  • Run on a schedule, right after the load

Let's see the unique key test do its job. A bad sync sends Sara twice.

seeds/customers.csv
customer_id,name,city,updated_at
1,Ali,Denver,2026-02-15 10:00:00
2,Sara,San Antonio,2025-04-10 14:30:00
2,Sara,Austin,2026-06-20 09:00:00
4,Maria,El Paso,2026-06-01 08:00:00
Terminal
$ dbt seed -s customers
 Succeeded seed  main.customers (table)

Finished 'seed' successfully for target 'dev'
Processed: 1 seed
Summary: 1 total | 1 success

Now we run dbt build with a plus in front of the snapshot. That also selects the source and its tests.

Terminal (expected error)
$ dbt build -s +customers_snapshot
    Passed test  source_not_null_app_db_customers_customer_id
    Failed test  source_unique_app_db_customers_customer_id (models/sources.yml:9:17)
   Skipped snapshot main_snapshots.customers_snapshot (snapshot)

====================== Test Failures =======================
Test failed (1 failed row(s)): source_unique_app_db_customers_customer_id

Finished 'build' with 1 error for target 'dev'
Processed: 2 tests | 1 snapshot
Summary: 3 total | 1 success | 1 error | 1 skipped

The unique test on the source fails with 1 failed row(s), so the snapshot is skipped: 1 error | 1 skipped. The duplicate never reaches the history.

Pitfall

Without that test, a duplicate key can fail the merge on some warehouses, or quietly write two current versions of the same customer.

Scenario 7: The source system was down for a week and then sent all the changes at once. What happens to your snapshot, and how do you check it?

A snapshot sees only the state at run time. So the changes in between two runs are never captured, and that week will have gaps.

Let's walk through it:

  • Source down a week: the daily snapshots find nothing new
  • Backlog lands: several changes per row, all at once
  • Next snapshot run: one final state per row

So if Ali moved twice during that week, only his last city reaches the snapshot. The middle version is lost for good. Here the catch-up load moves Ali to Seattle and adds a new customer, Omar. We seed and snapshot.

seeds/customers.csv
customer_id,name,city,updated_at
1,Ali,Seattle,2026-07-05 17:20:00
2,Sara,San Antonio,2025-04-10 14:30:00
4,Maria,El Paso,2026-06-01 08:00:00
5,Omar,Tucson,2026-07-03 13:10:00
Terminal
$ dbt seed -s customers
 Succeeded seed  main.customers (table)

Finished 'seed' successfully for target 'dev'
Processed: 1 seed
Summary: 1 total | 1 success
$ dbt snapshot
 Succeeded snapshot main_snapshots.customers_check_snapshot (snapshot)
 Succeeded snapshot main_snapshots.customers_snapshot (snapshot)

Finished 'snapshot' successfully for target 'dev'
Processed: 2 snapshots
Summary: 2 total | 2 success
SQL - check the table (DuckDB)
select customer_id, name, city, dbt_valid_from, dbt_valid_to
from main_snapshots.customers_snapshot
where customer_id in (1, 5)
order by customer_id, dbt_valid_from
Result4 rows
customer_idnamecitydbt_valid_fromdbt_valid_to
1AliDallas2025-03-01 09:002026-02-15 10:00
1AliDenver2026-02-15 10:002026-07-05 17:20
1AliSeattle2026-07-05 17:209999-12-31 00:00
5OmarTucson2026-07-03 13:109999-12-31 00:00

The timestamp strategy saves the dates. Ali's Seattle row starts at 2026-07-05 17:20, and Omar's at 2026-07-03 13:10: the real change times, not the load date. With check, every change would get the catch-up date.

Then we check it. dbt_scd_id must be unique, and a singular test checks that each version ends where the next one starts, and only the last one is current. We run dbt test on the snapshot.

snapshots/customers_snapshot.yml
snapshots:
  - name: customers_snapshot
    relation: source('app_db', 'customers')
    config:
      schema: snapshots
      strategy: timestamp
      unique_key: customer_id
      updated_at: updated_at
      hard_deletes: new_record
      dbt_valid_to_current: "cast('9999-12-31' as timestamp)"
    columns:
      - name: dbt_scd_id
        data_tests:
          - unique
tests/valid_ranges_have_no_gaps_or_overlaps.sql
select customer_id, dbt_valid_from, dbt_valid_to
from (
  select customer_id, dbt_valid_from, dbt_valid_to,
    lead(dbt_valid_from) over (
      partition by customer_id order by dbt_valid_from
    ) as next_valid_from
  from {{ ref('customers_snapshot') }}
)
-- each version ends where the next one starts,
-- and only the last one is current
where dbt_valid_to is distinct from
  coalesce(next_valid_from, cast('9999-12-31' as timestamp))
Terminal
$ dbt test -s customers_snapshot
    Passed test  unique_customers_snapshot_dbt_scd_id
    Passed test  valid_ranges_have_no_gaps_or_overlaps

Finished 'test' successfully for target 'dev'
Processed: 2 tests
Summary: 2 total | 2 success

Both tests pass: 2 total | 2 success. Then close the loop:

  • Tell the business: that week has gaps
  • Need every change? The fix is upstream: a change feed or an audit table, loaded incrementally
  • Source freshness: flags the outage on day one

Key points to remember

  • A snapshot keeps SCD Type 2 history of a source that overwrites rows
  • timestamp when updated_at is reliable; check with explicit check_cols
  • hard_deletes and dbt_valid_to_current: decide on day one
  • Join facts with a point-in-time range: >= valid_from, < valid_to
  • Test the unique key first: a snapshot only sees what exists when it runs

The full script

Here is a Python script that writes the whole project and runs every dbt command above in order; run pip install dbt first.

Show the full script that builds this project and runs every step
Full script - pip install dbt, then run it with Python in an empty folder
# ========================================================================
# dbt Interview Q&A #5 - Snapshots and SCD Type 2
# TechBrothersIT. Sample data is invented for teaching.
# Every step below was run with dbt v2 (dbt OSS 2.0.8) on DuckDB; the outputs in the video and the
# blog post are the real outputs. To run it yourself, in an empty folder:
#   pip install dbt     (dbt v2; adapters are bundled, and DuckDB needs no account or server)
#   python dbt_Interview_QA_05_Code.py
# ========================================================================

import os, subprocess

def write(path, text):
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(text.strip("\n") + "\n")

def remove(path):
    if os.path.exists(path):
        os.remove(path)

def dbt(cmd, expect_error=False):
    print("\n$ " + cmd, flush=True)
    rc = subprocess.run(cmd, shell=True).returncode
    if rc != 0 and not expect_error:
        raise SystemExit("stopped: this command was expected to succeed")

# Step 0: the project and its sample data
write('dbt_project.yml', """\
name: shop
version: '1.0'
profile: shop
""")
write('seeds/customers.csv', """\
customer_id,name,city,updated_at
1,Ali,Dallas,2025-03-01 09:00:00
2,Sara,Austin,2025-04-10 14:30:00
3,John,Houston,2025-05-20 11:15:00
""")
write('models/sources.yml', """\
sources:
  - name: app_db
    schema: main  # in this demo, dbt seed loads the app tables here
    tables:
      - name: customers
        columns:
          - name: customer_id
            data_tests:
              - unique
              - not_null
      - name: orders
""")
write('snapshots/customers_snapshot.yml', """\
snapshots:
  - name: customers_snapshot
    relation: source('app_db', 'customers')
    config:
      schema: snapshots
      strategy: timestamp
      unique_key: customer_id
      updated_at: updated_at
      hard_deletes: new_record
""")
write('snapshots/customers_check_snapshot.yml', """\
snapshots:
  - name: customers_check_snapshot
    relation: source('app_db', 'customers')
    config:
      schema: snapshots
      strategy: check
      unique_key: customer_id
      check_cols: [city]
""")
write('profiles.yml', """\
shop:
  target: dev
  outputs:
    dev:
      type: duckdb
      path: dev.duckdb
      threads: 1
""")

# Step 1: Load the source and take the first snapshot
dbt('dbt seed')
dbt('dbt snapshot')

# Step 2: Ali moves from Dallas to Denver: snapshot again
write('seeds/customers.csv', """\
customer_id,name,city,updated_at
1,Ali,Denver,2026-02-15 10:00:00
2,Sara,Austin,2025-04-10 14:30:00
3,John,Houston,2025-05-20 11:15:00
""")
dbt('dbt seed')
dbt('dbt snapshot')

# Step 3: The city of every customer as of December 31, 2025
write('models/customers_as_of.sql', """\
{% set as_of = "timestamp '2025-12-31'" %}

select customer_id, name, city
from {{ ref('customers_snapshot') }}
where dbt_valid_from <= {{ as_of }}
  and (dbt_valid_to > {{ as_of }} or dbt_valid_to is null)
  and dbt_is_deleted = 'False'
""")
dbt('dbt show -s customers_as_of')

# Step 4: Sara's city changes, but updated_at is not bumped
write('seeds/customers.csv', """\
customer_id,name,city,updated_at
1,Ali,Denver,2026-02-15 10:00:00
2,Sara,San Antonio,2025-04-10 14:30:00
3,John,Houston,2025-05-20 11:15:00
""")
dbt('dbt seed')
dbt('dbt snapshot')

# Step 5: John is deleted in the source
write('seeds/customers.csv', """\
customer_id,name,city,updated_at
1,Ali,Denver,2026-02-15 10:00:00
2,Sara,San Antonio,2025-04-10 14:30:00
""")
dbt('dbt seed')
dbt('dbt snapshot')

# Step 6: Orders joined to the snapshot on the key only
write('seeds/orders.csv', """\
order_id,customer_id,amount,ordered_at
101,1,120.00,2025-11-05 12:00:00
102,1,80.00,2026-03-01 09:30:00
103,2,45.00,2025-12-01 16:45:00
""")
write('models/fct_orders.sql', """\
select o.order_id, o.customer_id, o.amount, o.ordered_at, c.city
from {{ source('app_db', 'orders') }} as o
left join {{ ref('customers_snapshot') }} as c
  on o.customer_id = c.customer_id
""")
dbt('dbt seed -s orders')
dbt('dbt run -s fct_orders')

# Step 7: The point-in-time join: the key and the validity range
write('models/fct_orders.sql', """\
select o.order_id, o.customer_id, o.amount, o.ordered_at, c.city
from {{ source('app_db', 'orders') }} as o
left join {{ ref('customers_snapshot') }} as c
  on o.customer_id = c.customer_id
 and o.ordered_at >= c.dbt_valid_from
 and (o.ordered_at < c.dbt_valid_to or c.dbt_valid_to is null)
""")
dbt('dbt run -s fct_orders')

# Step 8: Add dbt_valid_to_current to the existing snapshot, then a new customer arrives
write('snapshots/customers_snapshot.yml', """\
snapshots:
  - name: customers_snapshot
    relation: source('app_db', 'customers')
    config:
      schema: snapshots
      strategy: timestamp
      unique_key: customer_id
      updated_at: updated_at
      hard_deletes: new_record
      dbt_valid_to_current: "cast('9999-12-31' as timestamp)"
""")
write('seeds/customers.csv', """\
customer_id,name,city,updated_at
1,Ali,Denver,2026-02-15 10:00:00
2,Sara,San Antonio,2025-04-10 14:30:00
4,Maria,El Paso,2026-06-01 08:00:00
""")
dbt('dbt seed -s customers')
dbt('dbt snapshot')

# Step 9: Backfill the old NULLs once with a run-operation
write('macros/backfill_valid_to.sql', """\
{% macro backfill_valid_to() %}
  {% set sql %}
    update {{ ref('customers_snapshot') }}
    set dbt_valid_to = cast('9999-12-31' as timestamp)
    where dbt_valid_to is null
  {% endset %}
  {% do run_query(sql) %}
  {{ log('backfilled dbt_valid_to on the current rows', info=True) }}
{% endmacro %}
""")
dbt('dbt run-operation backfill_valid_to')

# Step 10: A bad sync sends Sara twice
write('seeds/customers.csv', """\
customer_id,name,city,updated_at
1,Ali,Denver,2026-02-15 10:00:00
2,Sara,San Antonio,2025-04-10 14:30:00
2,Sara,Austin,2026-06-20 09:00:00
4,Maria,El Paso,2026-06-01 08:00:00
""")
dbt('dbt seed -s customers')

# Step 11: Build the snapshot with its source tests: the unique test fails, the snapshot is skipped
dbt('dbt build -s +customers_snapshot', expect_error=True)   # EXPECTED TO FAIL: the video shows this error

# Step 12: After a week-long outage, the source sends everything at once
write('seeds/customers.csv', """\
customer_id,name,city,updated_at
1,Ali,Seattle,2026-07-05 17:20:00
2,Sara,San Antonio,2025-04-10 14:30:00
4,Maria,El Paso,2026-06-01 08:00:00
5,Omar,Tucson,2026-07-03 13:10:00
""")
dbt('dbt seed -s customers')
dbt('dbt snapshot')

# Step 13: Check the snapshot: a unique dbt_scd_id, and no gaps or overlaps in the valid ranges
write('snapshots/customers_snapshot.yml', """\
snapshots:
  - name: customers_snapshot
    relation: source('app_db', 'customers')
    config:
      schema: snapshots
      strategy: timestamp
      unique_key: customer_id
      updated_at: updated_at
      hard_deletes: new_record
      dbt_valid_to_current: "cast('9999-12-31' as timestamp)"
    columns:
      - name: dbt_scd_id
        data_tests:
          - unique
""")
write('tests/valid_ranges_have_no_gaps_or_overlaps.sql', """\
select customer_id, dbt_valid_from, dbt_valid_to
from (
  select customer_id, dbt_valid_from, dbt_valid_to,
    lead(dbt_valid_from) over (
      partition by customer_id order by dbt_valid_from
    ) as next_valid_from
  from {{ ref('customers_snapshot') }}
)
-- each version ends where the next one starts,
-- and only the last one is current
where dbt_valid_to is distinct from
  coalesce(next_valid_from, cast('9999-12-31' as timestamp))
""")
dbt('dbt test -s customers_snapshot')
Next in this series

Part 6: Jinja, Macros and Packages

The sample data on this page is invented for teaching. Every terminal output is the real output of the dbt command above it, run with dbt v2 (dbt OSS 2.0.8) on DuckDB; run times and node counters are left out, and node lines are listed in DAG order. Part of the Real Time dbt Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of October 2026; check the official dbt documentation (docs.getdbt.com) for anything you quote in an interview.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.