In this post we are going to cover dbt fundamentals and project structure, through 7 real dbt interview questions for data engineers, asked the way they come up on a real project. The last one is a scenario: your team has a folder of stored procedures that build the reporting tables, and you have to move them into dbt.
dbt is the transformation tool in a modern data stack. You write each transformation as a select statement, and dbt builds it in the warehouse as a view or a table, in the right order, with tests. Interviewers start here because everything else in dbt, from ref to tests to deployment, builds on these basics.
Part 1 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: Your manager asks what dbt actually does in the data stack, and whether it replaces your loading tool. What do you say?
- Question 2: A new teammate hard-codes a table name instead of using ref. Why does ref matter, and what does it give you?
- Question 3: Raw tables are referenced by name in fifty models. When do you use source instead of ref?
- Question 4: The project has two hundred models in one folder. How do you structure staging, intermediate and mart models?
- Question 5: A teammate asks what the difference is between dbt run and dbt build. What do you tell them?
- Question 6: A model fails and nobody can see the SQL that ran. How do you find the compiled SQL and debug it?
- Scenario 7: Your team has a folder of stored procedures that build the reporting tables. How do you move them into dbt?
- The full script
The short answer
dbt is the T in ELT: you write select statements, and dbt builds them as views and tables in the warehouse, in dependency order, with tests. ref() links models and resolves the right schema per environment, source() declares raw tables, and dbt build runs models and tests together, so a failing test stops bad data from flowing downstream.
Let's create the project and some sample data
Our project is a small shop: customers, orders and payments land as raw tables, and dbt turns them into staging views, one intermediate view and two mart tables. There is also a small seed with payment method names. Here are all the starting files.
name: shop
version: '1.0'
profile: shop
models:
shop:
staging:
+materialized: view
intermediate:
+materialized: view
marts:
+materialized: tableshop:
target: dev
outputs:
dev:
type: duckdb
path: shop.duckdb
schema: dbt_sara
threads: 1
prod:
type: duckdb
path: shop.duckdb
schema: analytics
threads: 1customer_id,name,city
10,Ali Khan,Dallas
11,Sara Lee,Austin
12,John Smith,Houstonorder_id,customer_id,order_date,status
1001,10,2026-10-01,shipped
1002,11,2026-10-01,shipped
1003,10,2026-10-02,placed
1004,12,2026-10-03,shipped
1005,12,2026-10-04,returnedpayment_id,order_id,method,amount
1,1001,card,120.25
2,1002,bank,80.36
3,1003,card,45.99
4,1004,gift,30.15
5,1005,card,52.40customer_id,lifetime_value
10,166.24
11,80.36
12,30.15{# Demo only: stands in for the loading tool. It lands the raw tables, #}
{# and the old procedure's output table, straight from the CSV files. #}
{% macro load_raw() %}
{% set tables = {
'raw.customers': 'customers',
'raw.orders': 'orders',
'raw.payments': 'payments',
'rpt.customer_revenue': 'legacy_customer_revenue'} %}
{% do run_query("create schema if not exists raw") %}
{% do run_query("create schema if not exists rpt") %}
{% for table, file in tables.items() %}
{% do run_query("create or replace table " ~ table ~
" as select * from read_csv('loader/" ~ file ~ ".csv')") %}
{% endfor %}
{{ log("raw tables loaded", info=True) }}
{% endmacro %}method,method_name
card,Credit card
bank,Bank transfer
gift,Gift cardsources:
- name: shop_raw
schema: raw
tables:
- name: customers
- name: orders
- name: paymentsmodels:
- name: stg_orders
columns:
- name: order_id
data_tests:
- unique
- not_null
- name: stg_payments
columns:
- name: payment_id
data_tests:
- unique
- not_nullselect
customer_id,
name as customer_name,
city
from {{ source('shop_raw', 'customers') }}select
order_id,
customer_id,
cast(order_date as date) as order_date,
status
from {{ source('shop_raw', 'orders') }}select
payment_id,
order_id,
method,
cast(amount as decimal(10, 2)) as amount
from {{ source('shop_raw', 'payments') }}select
p.order_id,
max(m.method_name) as paid_with,
sum(p.amount) as amount_paid
from {{ ref('stg_payments') }} as p
left join {{ ref('payment_methods') }} as m
on p.method = m.method
group by p.order_idselect
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid
from {{ ref('stg_orders') }} as o
left join {{ ref('int_order_payments') }} as p
on o.order_id = p.order_idselect
c.customer_id,
c.customer_name,
c.city,
count(o.order_id) as orders,
sum(o.amount_paid) as lifetime_value
from {{ ref('stg_customers') }} as c
left join {{ ref('fct_orders') }} as o
on c.customer_id = o.customer_id
and o.status <> 'returned'
group by c.customer_id, c.customer_name, c.cityIn a real project a loading tool lands the raw tables. Here a small demo macro stands in for it, so first we run dbt run-operation load_raw.
$ dbt run-operation load_raw
raw tables loaded
Finished 'run-operation' successfully for target 'dev'The raw tables are in place, so now we can start with the questions.
Question 1: Your manager asks what dbt actually does in the data stack, and whether it replaces your loading tool. What do you say?
dbt is the T in ELT. It does not extract or load anything, so no, it does not replace the loading tool.
Let's look at where it sits. First, a loading tool like Fivetran, Airbyte or Azure Data Factory extracts data from the source systems, like the shop app or the CRM, and lands it raw in the warehouse. dbt starts there. You write each transformation as a select statement in a model file. dbt turns it into a view or a table, works out the build order, and runs your tests. dbt compiles each model to SQL and runs it in the warehouse, so the warehouse does all the compute.
Our staging models are just a select from a raw table. Let's run dbt build on the whole project.
$ dbt build
Succeeded seed dbt_sara.payment_methods (table)
Succeeded model dbt_sara.stg_customers (view)
Succeeded model dbt_sara.stg_orders (view)
Succeeded model dbt_sara.stg_payments (view)
Passed test not_null_stg_orders_order_id
Passed test not_null_stg_payments_payment_id
Passed test unique_stg_orders_order_id
Passed test unique_stg_payments_payment_id
Succeeded model dbt_sara.int_order_payments (view)
Succeeded model dbt_sara.fct_orders (table)
Succeeded model dbt_sara.dim_customers (table)
Finished 'build' successfully for target 'dev'
Processed: 6 models | 4 tests | 1 seed
Summary: 11 total | 11 successdbt loads one seed, builds six models as views and tables, and runs four tests. The summary line says it: 11 total | 11 success.
So the loader and dbt work together. In a real project the order is:
- Loader: lands the raw data
- dbt job: on the dbt platform or in an orchestrator like Airflow, transforms what just landed
Say "the loader does E and L, dbt does T, and the warehouse does the compute". That one line answers both halves of the question.
Question 2: A new teammate hard-codes a table name instead of using ref. Why does ref matter, and what does it give you?
ref is how dbt knows how your models depend on each other, and it points each model at the right schema for the environment you run in. A hard-coded name gives you neither.
Let's see the problem first. Here is the teammate's fct_orders, reading from dbt_sara.stg_orders, a schema typed by hand. We ask dbt for this model and everything upstream with dbt ls -s +fct_orders.
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid
from dbt_sara.stg_orders as o
left join dbt_sara.int_order_payments as p
on o.order_id = p.order_id$ dbt ls -s +fct_orders --resource-type model
=======================Selected nodes=======================
shop.marts.fct_orders
Finished 'list' successfully for target 'dev'dbt lists only shop.marts.fct_orders. It has no parents at all. It gets worse. Now we compile and build it for the prod target.
$ dbt compile -s fct_orders --target prod
Compiled node 'fct_orders' is:
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid
from dbt_sara.stg_orders as o
left join dbt_sara.int_order_payments as p
on o.order_id = p.order_id
Finished 'compile' successfully for target 'prod'
Processed: 1 model
Summary: 1 total | 1 success
$ dbt build -s fct_orders --target prod
Succeeded model analytics.fct_orders (table)
Finished 'build' successfully for target 'prod'
Processed: 1 model
Summary: 1 total | 1 successThe compiled SQL still reads from dbt_sara, Sara's dev schema, and the build succeeds: analytics.fct_orders is a production table built from a developer's data, with no error at all. Now let's put ref back and run the same list command.
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid
from {{ ref('stg_orders') }} as o
left join {{ ref('int_order_payments') }} as p
on o.order_id = p.order_id$ dbt ls -s +fct_orders --resource-type model
=======================Selected nodes=======================
shop.marts.fct_orders
shop.intermediate.int_order_payments
shop.staging.stg_orders
shop.staging.stg_payments
Finished 'list' successfully for target 'dev'This time dbt shows the whole chain: int_order_payments, stg_orders and stg_payments. Then we compile it for prod again.
$ dbt compile -s fct_orders --target prod
Compiled node 'fct_orders' is:
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid
from "shop"."analytics"."stg_orders" as o
left join "shop"."analytics"."int_order_payments" as p
on o.order_id = p.order_id
Finished 'compile' successfully for target 'prod'
Processed: 1 model
Summary: 1 total | 1 successEvery ref now points at "shop"."analytics". So ref gives you three things:
- The dependency graph: the build order, and selectors like
+fct_orders - The right table per environment:
dbt_sarain dev,analyticsin prod, which is also what lets defer and slim CI work later - Lineage in the docs, from source to mart
No schema name is ever typed in a model. Raw tables use source(), and everything dbt builds uses ref().
Question 3: Raw tables are referenced by name in fifty models. When do you use source instead of ref?
Use source for tables dbt did not build, the raw tables your loader lands. Use ref for everything dbt builds: models, seeds and snapshots.
| source() | ref() | |
|---|---|---|
| POINTS AT | tables dbt did not build | models, seeds, snapshots |
| EXAMPLE | source('shop_raw', 'orders') | ref('stg_orders') |
First, you declare the raw tables once in a sources YAML file: the source name, the schema and the tables. Our _sources.yml declares shop_raw in the raw schema. The staging model then selects from source('shop_raw', 'orders'). If the raw schema moves, you change one line, not fifty models.
Sources are nodes in the DAG too. Let's ask dbt for every model downstream of the raw payments table with dbt ls -s source:shop_raw.payments+.
$ dbt ls -s source:shop_raw.payments+ --resource-type model
=======================Selected nodes=======================
shop.marts.dim_customers
shop.marts.fct_orders
shop.intermediate.int_order_payments
shop.staging.stg_payments
Finished 'list' successfully for target 'dev'dbt lists stg_payments, int_order_payments, fct_orders and dim_customers. That is your blast radius when the loader changes that table.
dbt also checks the names when it parses the project. Let's put a typo in the source name, order instead of orders, and build the staging model.
select
order_id,
customer_id,
cast(order_date as date) as order_date,
status
from {{ source('shop_raw', 'order') }}$ dbt build -s stg_orders
=================== Errors and Warnings ====================
[error] [DependencyNotFound (dbt1048)]: Source 'shop_raw.order' not found in project. Searched for
'shop.shop_raw.order, shop_raw.order'
--> models/staging/stg_orders.sql:6:6
Finished 'build' with 1 error for target 'dev'It fails before any SQL runs, with Source 'shop_raw.order' not found in project, and dbt v2 points to the file, the line and the column: models/staging/stg_orders.sql:6:6. Then we fix the name.
select
order_id,
customer_id,
cast(order_date as date) as order_date,
status
from {{ source('shop_raw', 'orders') }}Sources also give you freshness checks on raw data. On a real project:
- Only staging models select from sources
- One staging model per raw table
- Everything after staging uses ref
Question 4: The project has two hundred models in one folder. How do you structure staging, intermediate and mart models?
I use the three layers from the dbt best practices guide: staging, intermediate and marts, each in its own folder, and data only flows forward.
Let's go layer by layer.
- Staging: one to one with the raw tables. Rename, cast and light cleanup, no joins. Prefix them
stg_, add the source name once you have several sources, keep a subfolder per source system, and build them as views. Ours arestg_customers,stg_ordersandstg_payments. - Intermediate: reusable logic, like
int_order_payments, which rolls payments up to one row per order and joins thepayment_methodsseed. These are building blocks, not something the BI tool queries. - Marts: what the business queries. Facts and dimensions, grouped by domain like finance or marketing, and built as tables. Ours are
fct_ordersanddim_customers.
Our dbt_project.yml sets the materialization for each folder, so no model repeats it. And the folders become selectors. Let's list the models by path.
$ dbt ls --resource-type model --output path
=======================Selected nodes=======================
models/marts/dim_customers.sql
models/marts/fct_orders.sql
models/intermediate/int_order_payments.sql
models/staging/stg_customers.sql
models/staging/stg_orders.sql
models/staging/stg_payments.sql
Finished 'list' successfully for target 'dev'We see the three folders: models/marts, models/intermediate and models/staging. Now we select just one folder with dbt ls -s marts.
$ dbt ls -s marts
=======================Selected nodes=======================
shop.marts.dim_customers
shop.marts.fct_orders
Finished 'list' successfully for target 'dev'dbt picks dim_customers and fct_orders, and nothing else.
With two hundred models, a domain folder under marts is one command: you can build or test just finance without touching the rest.
Question 5: A teammate asks what the difference is between dbt run and dbt build. What do you tell them?
dbt run only builds models. dbt build does everything in one DAG: seeds, models, snapshots and tests, and a failing test stops the models downstream of it.
| dbt run | dbt build | |
|---|---|---|
| BUILDS | models only | seeds, models, snapshots and tests |
| A TEST FAILS | tests never run | downstream models are skipped |
Let's see why that matters. The loader resends a payment, so payment 2 lands in the raw table twice. We land the data again with dbt run-operation load_raw.
payment_id,order_id,method,amount
1,1001,card,120.25
2,1002,bank,80.36
2,1002,bank,80.36
3,1003,card,45.99
4,1004,gift,30.15
5,1005,card,52.40$ dbt run-operation load_raw
raw tables loaded
Finished 'run-operation' successfully for target 'dev'First we run dbt build on that data.
$ dbt build
Succeeded seed dbt_sara.payment_methods (table)
Succeeded model dbt_sara.stg_customers (view)
Succeeded model dbt_sara.stg_orders (view)
Succeeded model dbt_sara.stg_payments (view)
Passed test not_null_stg_orders_order_id
Passed test not_null_stg_payments_payment_id
Passed test unique_stg_orders_order_id
Failed test unique_stg_payments_payment_id (models/staging/_staging.yml:12:13)
Skipped model dbt_sara.int_order_payments (view)
Skipped model dbt_sara.fct_orders (table)
Skipped model dbt_sara.dim_customers (table)
====================== Test Failures =======================
Test failed (1 failed row(s)): unique_stg_payments_payment_id
Finished 'build' with 1 error for target 'dev'
Processed: 6 models | 4 tests | 1 seed
Summary: 11 total | 7 success | 1 error | 3 skippedThe unique test on payment_id fails, and dbt skips int_order_payments, fct_orders and dim_customers, so the mart tables are not rebuilt from the bad data. The summary says it: 1 error | 3 skipped. Now the same data with dbt run, and then we look at dim_customers with dbt show.
$ dbt run
Succeeded model dbt_sara.stg_customers (view)
Succeeded model dbt_sara.stg_orders (view)
Succeeded model dbt_sara.stg_payments (view)
Succeeded model dbt_sara.int_order_payments (view)
Succeeded model dbt_sara.fct_orders (table)
Succeeded model dbt_sara.dim_customers (table)
Finished 'run' successfully for target 'dev'
Processed: 6 models
Summary: 6 total | 6 success
$ dbt show --inline "select * from {{ ref('dim_customers') }} order by 1"
Query show_sql_operation_inline
┌─────────────┬───────────────┬─────────┬────────┬────────────────┐
│ customer_id ┆ customer_name ┆ city ┆ orders ┆ lifetime_value │
╞═════════════╪═══════════════╪═════════╪════════╪════════════════╡
│ 10 ┆ Ali Khan ┆ Dallas ┆ 2 ┆ 166.24 │
│ 11 ┆ Sara Lee ┆ Austin ┆ 1 ┆ 160.72 │
│ 12 ┆ John Smith ┆ Houston ┆ 1 ┆ 30.15 │
└─────────────┴───────────────┴─────────┴────────┴────────────────┘
3 rows.
Succeeded model dbt_sara.inline (ephemeral)
Finished 'show' successfully for target 'dev'dbt run builds all six models without a word: 6 total | 6 success. But Sara Lee's lifetime value doubles, from 80.36 to 160.72. Then we fix the load and build again.
payment_id,order_id,method,amount
1,1001,card,120.25
2,1002,bank,80.36
3,1003,card,45.99
4,1004,gift,30.15
5,1005,card,52.40$ dbt run-operation load_raw
raw tables loaded
Finished 'run-operation' successfully for target 'dev'
$ dbt build
Succeeded seed dbt_sara.payment_methods (table)
Succeeded model dbt_sara.stg_customers (view)
Succeeded model dbt_sara.stg_orders (view)
Succeeded model dbt_sara.stg_payments (view)
Passed test not_null_stg_orders_order_id
Passed test not_null_stg_payments_payment_id
Passed test unique_stg_orders_order_id
Passed test unique_stg_payments_payment_id
Succeeded model dbt_sara.int_order_payments (view)
Succeeded model dbt_sara.fct_orders (table)
Succeeded model dbt_sara.dim_customers (table)
Finished 'build' successfully for target 'dev'
Processed: 6 models | 4 tests | 1 seed
Summary: 11 total | 11 successBack to 11 total | 11 success. So here is how I use them:
- Production:
dbt build, so tests guard every layer - Development:
dbt run -s one_model, while you iterate - Unit tests too: dbt build runs them with the rest of the DAG, so a logic bug stops the build before bad data lands
Question 6: A model fails and nobody can see the SQL that ran. How do you find the compiled SQL and debug it?
Read the error first: dbt names the model and the file under target/run that holds the SQL it ran. Then use dbt compile and dbt show to find the problem.
Let's break fct_orders by selecting a column that does not exist, amount_paid_usd, and run it.
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid_usd
from {{ ref('stg_orders') }} as o
left join {{ ref('int_order_payments') }} as p
on o.order_id = p.order_id$ dbt run -s fct_orders
Failed model dbt_sara.fct_orders (table)
=================== Errors and Warnings ====================
[error] [DbDriverFailed (dbt1308)]: Database Error in model fct_orders
(target/run/shop/models/marts/fct_orders.sql)
Binder Error: Values list "p" does not have a column named "amount_paid_usd"
LINE 16: p.amount_paid_usd
^
(in run/shop/models/marts/fct_orders.sql)
Finished 'run' with 1 error for target 'dev'
Processed: 1 model
Summary: 1 total | 1 errordbt names the model and the file, target/run/shop/models/marts/fct_orders.sql. That file holds your select, inside the create table statement dbt sent. The binder error says the column amount_paid_usd does not exist. Be careful with the line number: LINE 16 counts the whole statement dbt sent, wrapper included. In your model file it is line 7.
Then we run dbt compile. It renders the Jinja without running the model, so it works even when the SQL is broken.
$ dbt compile -s fct_orders
Compiled node 'fct_orders' is:
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid_usd
from "shop"."dbt_sara"."stg_orders" as o
left join "shop"."dbt_sara"."int_order_payments" as p
on o.order_id = p.order_id
Finished 'compile' successfully for target 'dev'
Processed: 1 model
Summary: 1 total | 1 successIt prints the select with every ref resolved to "shop"."dbt_sara", and writes it to target/compiled. Paste it into the warehouse's query editor and debug there. Next we check the input with dbt show, which runs a select and prints the rows without building anything.
$ dbt show --inline "select * from {{ ref('int_order_payments') }} order by order_id" --limit 2
Query show_sql_operation_inline
┌──────────┬───────────────┬─────────────┐
│ order_id ┆ paid_with ┆ amount_paid │
╞══════════╪═══════════════╪═════════════╡
│ 1001 ┆ Credit card ┆ 120.25 │
│ 1002 ┆ Bank transfer ┆ 80.36 │
└──────────┴───────────────┴─────────────┘
2 rows, showing only 2 rows. Run with --limit -1 to show all rows.
Succeeded model dbt_sara.inline (ephemeral)
Finished 'show' successfully for target 'dev'The intermediate model has amount_paid, not amount_paid_usd. Let's fix the column and run the model again.
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid
from {{ ref('stg_orders') }} as o
left join {{ ref('int_order_payments') }} as p
on o.order_id = p.order_id$ dbt run -s fct_orders
Succeeded model dbt_sara.fct_orders (table)
Finished 'run' successfully for target 'dev'
Processed: 1 model
Summary: 1 total | 1 successIt builds: 1 total | 1 success.
logs/dbt.log keeps every query dbt ran. In CI, save the target/ folder and the log as job artifacts, so you can see the SQL after the job is gone.
Scenario 7: Your team has a folder of stored procedures that build the reporting tables. How do you move them into dbt?
Not all at once. Move one procedure at a time, prove the new model matches the old table, and only then retire the procedure.
First, plan the order:
- One procedure at a time
- Most important reports first
- Write down what each one reads and writes
Here is the old procedure. It builds rpt.customer_revenue from raw orders and payments.
CREATE PROCEDURE rpt.usp_customer_revenue AS
BEGIN
TRUNCATE TABLE rpt.customer_revenue;
SELECT order_id, SUM(amount) AS amount_paid
INTO #paid
FROM raw.payments
GROUP BY order_id;
INSERT INTO rpt.customer_revenue
SELECT o.customer_id, SUM(p.amount_paid)
FROM raw.orders AS o
JOIN #paid AS p ON p.order_id = o.order_id
WHERE o.status <> 'returned'
GROUP BY o.customer_id;
END;Then map the pieces. Hard-coded raw tables become sources. Each temp table becomes a CTE or an intermediate model. Truncate and insert becomes a table, a merge becomes incremental, and the call order becomes refs.
| Stored procedure | dbt | |
|---|---|---|
| RAW TABLES | raw.orders, raw.payments by name | source() |
| TEMP TABLES | #paid | a CTE or an intermediate model |
| TRUNCATE + INSERT | rebuild the table | materialized: table |
| MERGE | upsert the changes | incremental, if a rebuild is too slow |
| CALL ORDER | EXEC one after another | ref() builds the DAG |
The logic of this procedure now lives in our dim_customers mart. To prove they match, we declare the legacy table as a source and add a singular test. It compares the legacy table with the new model both ways, with except. Any row it returns is a difference.
sources:
- name: legacy
schema: rpt
tables:
- name: customer_revenue-- the old procedure's table vs the new mart, both ways:
-- every row returned is a difference, so 0 rows = a pass
with legacy as (
select customer_id, cast(lifetime_value as decimal(10, 2)) as ltv
from {{ source('legacy', 'customer_revenue') }}
),
new as (
select customer_id, lifetime_value as ltv
from {{ ref('dim_customers') }}
)
(select * from legacy except select * from new)
union all
(select * from new except select * from legacy)Now we build the mart with dbt build -s dim_customers, which also runs the audit test.
$ dbt build -s dim_customers
Succeeded model dbt_sara.dim_customers (table)
Passed test audit_customer_revenue
Finished 'build' successfully for target 'dev'
Processed: 1 model | 1 test
Summary: 2 total | 2 successThe audit test passes: zero differences. On real data the first compare usually finds some, often bugs in the old code, so agree on each one with the business. Then:
- Run both side by side, with the audit test on each build
- Switch the dashboards
- Retire the procedure
On real tables, the audit_helper package shows which columns differ, not just which rows.
Key points to remember
- dbt is the T in ELT: the loader lands data, dbt transforms it
- ref(): the DAG, build order, the right schema per target
- source() for raw tables; ref() for models, seeds, snapshots
- Layers: staging, intermediate, marts; folders as selectors
- dbt build runs tests in the DAG; read target/run and dbt compile
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 #1 - dbt fundamentals and project structure
# 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_01_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
models:
shop:
staging:
+materialized: view
intermediate:
+materialized: view
marts:
+materialized: table
""")
write('profiles.yml', """\
shop:
target: dev
outputs:
dev:
type: duckdb
path: shop.duckdb
schema: dbt_sara
threads: 1
prod:
type: duckdb
path: shop.duckdb
schema: analytics
threads: 1
""")
write('loader/customers.csv', """\
customer_id,name,city
10,Ali Khan,Dallas
11,Sara Lee,Austin
12,John Smith,Houston
""")
write('loader/orders.csv', """\
order_id,customer_id,order_date,status
1001,10,2026-10-01,shipped
1002,11,2026-10-01,shipped
1003,10,2026-10-02,placed
1004,12,2026-10-03,shipped
1005,12,2026-10-04,returned
""")
write('loader/payments.csv', """\
payment_id,order_id,method,amount
1,1001,card,120.25
2,1002,bank,80.36
3,1003,card,45.99
4,1004,gift,30.15
5,1005,card,52.40
""")
write('loader/legacy_customer_revenue.csv', """\
customer_id,lifetime_value
10,166.24
11,80.36
12,30.15
""")
write('macros/load_raw.sql', """\
{# Demo only: stands in for the loading tool. It lands the raw tables, #}
{# and the old procedure's output table, straight from the CSV files. #}
{% macro load_raw() %}
{% set tables = {
'raw.customers': 'customers',
'raw.orders': 'orders',
'raw.payments': 'payments',
'rpt.customer_revenue': 'legacy_customer_revenue'} %}
{% do run_query("create schema if not exists raw") %}
{% do run_query("create schema if not exists rpt") %}
{% for table, file in tables.items() %}
{% do run_query("create or replace table " ~ table ~
" as select * from read_csv('loader/" ~ file ~ ".csv')") %}
{% endfor %}
{{ log("raw tables loaded", info=True) }}
{% endmacro %}
""")
write('seeds/payment_methods.csv', """\
method,method_name
card,Credit card
bank,Bank transfer
gift,Gift card
""")
write('models/staging/_sources.yml', """\
sources:
- name: shop_raw
schema: raw
tables:
- name: customers
- name: orders
- name: payments
""")
write('models/staging/_staging.yml', """\
models:
- name: stg_orders
columns:
- name: order_id
data_tests:
- unique
- not_null
- name: stg_payments
columns:
- name: payment_id
data_tests:
- unique
- not_null
""")
write('models/staging/stg_customers.sql', """\
select
customer_id,
name as customer_name,
city
from {{ source('shop_raw', 'customers') }}
""")
write('models/staging/stg_orders.sql', """\
select
order_id,
customer_id,
cast(order_date as date) as order_date,
status
from {{ source('shop_raw', 'orders') }}
""")
write('models/staging/stg_payments.sql', """\
select
payment_id,
order_id,
method,
cast(amount as decimal(10, 2)) as amount
from {{ source('shop_raw', 'payments') }}
""")
write('models/intermediate/int_order_payments.sql', """\
select
p.order_id,
max(m.method_name) as paid_with,
sum(p.amount) as amount_paid
from {{ ref('stg_payments') }} as p
left join {{ ref('payment_methods') }} as m
on p.method = m.method
group by p.order_id
""")
write('models/marts/fct_orders.sql', """\
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid
from {{ ref('stg_orders') }} as o
left join {{ ref('int_order_payments') }} as p
on o.order_id = p.order_id
""")
write('models/marts/dim_customers.sql', """\
select
c.customer_id,
c.customer_name,
c.city,
count(o.order_id) as orders,
sum(o.amount_paid) as lifetime_value
from {{ ref('stg_customers') }} as c
left join {{ ref('fct_orders') }} as o
on c.customer_id = o.customer_id
and o.status <> 'returned'
group by c.customer_id, c.customer_name, c.city
""")
# Step 1: Land the raw tables (a demo macro stands in for the loading tool)
dbt('dbt run-operation load_raw')
# Step 2: Build the whole project: seed, models and tests
dbt('dbt build')
# Step 3: A hard-coded table name: dbt sees no parents
write('models/marts/fct_orders.sql', """\
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid
from dbt_sara.stg_orders as o
left join dbt_sara.int_order_payments as p
on o.order_id = p.order_id
""")
dbt('dbt ls -s +fct_orders --resource-type model')
# Step 4: Compile and build it for prod: it still reads the dev schema
dbt('dbt compile -s fct_orders --target prod')
dbt('dbt build -s fct_orders --target prod')
# Step 5: The same model with ref: dbt knows the whole chain
write('models/marts/fct_orders.sql', """\
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid
from {{ ref('stg_orders') }} as o
left join {{ ref('int_order_payments') }} as p
on o.order_id = p.order_id
""")
dbt('dbt ls -s +fct_orders --resource-type model')
# Step 6: Compile it for prod: ref points at the prod schema
dbt('dbt compile -s fct_orders --target prod')
# Step 7: Everything downstream of one raw table
dbt('dbt ls -s source:shop_raw.payments+ --resource-type model')
# Step 8: A typo in a source name fails before any SQL runs
write('models/staging/stg_orders.sql', """\
select
order_id,
customer_id,
cast(order_date as date) as order_date,
status
from {{ source('shop_raw', 'order') }}
""")
dbt('dbt build -s stg_orders', expect_error=True) # EXPECTED TO FAIL: the video shows this error
# Step 9: Fix the source name
write('models/staging/stg_orders.sql', """\
select
order_id,
customer_id,
cast(order_date as date) as order_date,
status
from {{ source('shop_raw', 'orders') }}
""")
# Step 10: The models by folder: staging, intermediate, marts
dbt('dbt ls --resource-type model --output path')
# Step 11: A folder is a selector
dbt('dbt ls -s marts')
# Step 12: The loader resends a duplicate payment
write('loader/payments.csv', """\
payment_id,order_id,method,amount
1,1001,card,120.25
2,1002,bank,80.36
2,1002,bank,80.36
3,1003,card,45.99
4,1004,gift,30.15
5,1005,card,52.40
""")
dbt('dbt run-operation load_raw')
# Step 13: dbt build: the unique test fails and the models downstream are skipped
dbt('dbt build', expect_error=True) # EXPECTED TO FAIL: the video shows this error
# Step 14: dbt run builds every model, with the duplicate
dbt('dbt run')
dbt('dbt show --inline "select * from {{ ref(\'dim_customers\') }} order by 1"')
# Step 15: Fix the load and rebuild
write('loader/payments.csv', """\
payment_id,order_id,method,amount
1,1001,card,120.25
2,1002,bank,80.36
3,1003,card,45.99
4,1004,gift,30.15
5,1005,card,52.40
""")
dbt('dbt run-operation load_raw')
dbt('dbt build')
# Step 16: A model fails: read the error
write('models/marts/fct_orders.sql', """\
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid_usd
from {{ ref('stg_orders') }} as o
left join {{ ref('int_order_payments') }} as p
on o.order_id = p.order_id
""")
dbt('dbt run -s fct_orders', expect_error=True) # EXPECTED TO FAIL: the video shows this error
# Step 17: dbt compile prints the compiled SQL
dbt('dbt compile -s fct_orders')
# Step 18: dbt show: check the columns of the model upstream
dbt('dbt show --inline "select * from {{ ref(\'int_order_payments\') }} order by order_id" --limit 2')
# Step 19: Fix the column and run the model
write('models/marts/fct_orders.sql', """\
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
p.paid_with,
p.amount_paid
from {{ ref('stg_orders') }} as o
left join {{ ref('int_order_payments') }} as p
on o.order_id = p.order_id
""")
dbt('dbt run -s fct_orders')
# Step 20: Declare the legacy table and add an audit test
write('models/staging/_legacy_sources.yml', """\
sources:
- name: legacy
schema: rpt
tables:
- name: customer_revenue
""")
write('tests/audit_customer_revenue.sql', """\
-- the old procedure's table vs the new mart, both ways:
-- every row returned is a difference, so 0 rows = a pass
with legacy as (
select customer_id, cast(lifetime_value as decimal(10, 2)) as ltv
from {{ source('legacy', 'customer_revenue') }}
),
new as (
select customer_id, lifetime_value as ltv
from {{ ref('dim_customers') }}
)
(select * from legacy except select * from new)
union all
(select * from new except select * from legacy)
""")
# Step 21: Build the mart: the audit test compares it with the legacy table
dbt('dbt build -s dim_customers')
Part 2: Materializations: View, Table, Ephemeral and Incremental
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.