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
- Let's create the project and some sample data
- 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?
- Question 2: A teammate asks when to use the timestamp strategy and when to use the check strategy. What do you say?
- Question 3: Records deleted in the source still look current in the snapshot. How do you handle hard deletes?
- Question 4: A report joins facts to the snapshot and gets duplicate rows. How do you join to an SCD Type 2 table correctly?
- 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?
- Question 6: A snapshot was pointed at a messy source and now has wrong history. What are the best practices for snapshots?
- 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?
- The full script
The short answer
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.
name: shop
version: '1.0'
profile: shopcustomer_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:00sources:
- 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: orderssnapshots:
- name: customers_snapshot
relation: source('app_db', 'customers')
config:
schema: snapshots
strategy: timestamp
unique_key: customer_id
updated_at: updated_at
hard_deletes: new_recordsnapshots:
- 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.
$ 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 successselect customer_id, name, city, dbt_valid_from, dbt_valid_to
from main_snapshots.customers_snapshot
order by customer_id, dbt_valid_from| customer_id | name | city | dbt_valid_from | dbt_valid_to |
|---|---|---|---|---|
| 1 | Ali | Dallas | 2025-03-01 09:00 | NULL |
| 2 | Sara | Austin | 2025-04-10 14:30 | NULL |
| 3 | John | Houston | 2025-05-20 11:15 | NULL |
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.
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 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 successselect customer_id, name, city, dbt_valid_from, dbt_valid_to
from main_snapshots.customers_snapshot
order by customer_id, dbt_valid_from| customer_id | name | city | dbt_valid_from | dbt_valid_to |
|---|---|---|---|---|
| 1 | Ali | Dallas | 2025-03-01 09:00 | 2026-02-15 10:00 |
| 1 | Ali | Denver | 2026-02-15 10:00 | NULL |
| 2 | Sara | Austin | 2025-04-10 14:30 | NULL |
| 3 | John | Houston | 2025-05-20 11:15 | NULL |
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.
{% 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 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.
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 CHANGE | updated_at is newer | a check_cols value differs |
| DBT_VALID_FROM | the source updated_at | the snapshot run time |
| USE WHEN | every change bumps updated_at | no 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.
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 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 successwith 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| snapshot | city | is_current |
|---|---|---|
| customers_snapshot | Austin | true |
| customers_check_snapshot | Austin | false |
| customers_check_snapshot | San Antonio | true |
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_atis 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_deletes | when a row disappears from the source |
|---|---|
| ignore (default) | nothing: the last version stays current |
| invalidate | closes the last version: sets dbt_valid_to |
| new_record | closes 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.
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 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 successwith 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| snapshot | city | dbt_is_deleted | is_current |
|---|---|---|---|
| customers_check_snapshot | Houston | NULL | true |
| customers_snapshot | Houston | False | false |
| customers_snapshot | Houston | True | true |
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.
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:00select 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 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 successselect order_id, customer_id, amount, ordered_at, city
from fct_orders
order by order_id, city| order_id | customer_id | amount | ordered_at | city |
|---|---|---|---|---|
| 101 | 1 | 120 | 2025-11-05 12:00 | Dallas |
| 101 | 1 | 120 | 2025-11-05 12:00 | Denver |
| 102 | 1 | 80 | 2026-03-01 09:30 | Dallas |
| 102 | 1 | 80 | 2026-03-01 09:30 | Denver |
| 103 | 2 | 45 | 2025-12-01 16:45 | Austin |
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.
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 run -s fct_orders
Succeeded model main.fct_orders (view)
Finished 'run' successfully for target 'dev'
Processed: 1 model
Summary: 1 total | 1 successselect order_id, customer_id, amount, ordered_at, city
from fct_orders
order by order_id, city| order_id | customer_id | amount | ordered_at | city |
|---|---|---|---|---|
| 101 | 1 | 120 | 2025-11-05 12:00 | Dallas |
| 102 | 1 | 80 | 2026-03-01 09:30 | Denver |
| 103 | 2 | 45 | 2025-12-01 16:45 | Austin |
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_idon 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:
- 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)"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 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 successselect 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| customer_id | name | dbt_valid_to | dbt_is_deleted |
|---|---|---|---|
| 1 | Ali | NULL | False |
| 2 | Sara | NULL | False |
| 3 | John | NULL | True |
| 4 | Maria | 9999-12-31 00:00 | False |
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.
{% 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 run-operation backfill_valid_to
backfilled dbt_valid_to on the current rows
Finished 'run-operation' successfully for target 'dev'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| customer_id | name | dbt_valid_to | dbt_is_deleted |
|---|---|---|---|
| 1 | Ali | 9999-12-31 00:00 | False |
| 2 | Sara | 9999-12-31 00:00 | False |
| 3 | John | 9999-12-31 00:00 | True |
| 4 | Maria | 9999-12-31 00:00 | False |
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.
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_deleteschosen 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.
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 seed -s customers
Succeeded seed main.customers (table)
Finished 'seed' successfully for target 'dev'
Processed: 1 seed
Summary: 1 total | 1 successNow we run dbt build with a plus in front of the snapshot. That also selects the source and its tests.
$ 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 skippedThe 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.
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.
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 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 successselect 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| customer_id | name | city | dbt_valid_from | dbt_valid_to |
|---|---|---|---|---|
| 1 | Ali | Dallas | 2025-03-01 09:00 | 2026-02-15 10:00 |
| 1 | Ali | Denver | 2026-02-15 10:00 | 2026-07-05 17:20 |
| 1 | Ali | Seattle | 2026-07-05 17:20 | 9999-12-31 00:00 |
| 5 | Omar | Tucson | 2026-07-03 13:10 | 9999-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:
- 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:
- uniqueselect 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 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 successBoth 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
# ========================================================================
# 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')
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.