Lab: Sources, Staging Models and the ref() Graph
Build a small shop project on DuckDB: declare and test three raw tables as sources, write one staging model per table, join them in an intermediate model and two marts, run dbt build, then read the dependency graph with dbt ls and manifest.json and see what a hard-coded table name does to it.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Install dbt and create the project files
- Step 2: Load the raw tables
- Step 3: Declare the sources and test them
- Step 4: One staging model per source table
- Step 5: An intermediate model, a seed and two marts
- Step 6: Build and test everything with dbt build
- Step 7: Read the graph with dbt ls and manifest.json
- Step 8: What a hard-coded table name does
- Check your understanding
- Apply it
- Review prompt
Lessons of SQL Transformation with dbt
- Why Transformations Belong in Version-Controlled SQL Concept · 15 min
- Lab: Sources, Staging Models and the ref() Graph Lab · 30 min
- Materializations and Incremental Models Worked example · 25 min
- Snapshots, Macros and Keeping Jinja in Check Lab · 25 min
- Lab: Docs and dbt build in Pull-Request CI Lab · 25 min
- Check: Review a dbt Pull Request Knowledge check · 8 questions
What you will learn
- Structure a dbt project into sources, staging, intermediate and mart models linked with ref() and source(), and explain the resulting dependency graph.
Prerequisites: SQL Fundamentals
01. Goal and setup
In this lab you turn three raw tables of a small online shop (customers, orders and payments) into two marts: fct_orders, one row per order with the amount paid, and dim_customers, one row per customer with their order count and spend. On the way you declare the raw tables as sources, test them, write one staging model per table and put a shared join in an intermediate model. Then you inspect the graph dbt built from your ref() and source() calls.
The lab was tested with Python 3.12, dbt Core 1.12.7, dbt-duckdb 1.11.1 and DuckDB 1.5.6 on Linux. It builds on Why Transformations Belong in Version-Controlled SQL, which explains models, targets and the DAG. Everything runs locally in one DuckDB file; you need no database server. Run every command from inside the shop folder.
shop/
├── dbt_project.yml, profiles.yml
├── load_raw.py step 2: writes the raw tables
├── results.py, lineage.py steps 6-7: read dbt's output files
├── seeds/country_names.csv
└── models/
├── staging/ _sources.yml, _staging.yml, stg_*.sql
├── intermediate/ int_order_payments.sql
└── marts/ fct_orders.sql, dim_customers.sql02. Step 1: Install dbt and create the project files
mkdir shop && cd shop
python3 -m venv .venv && source .venv/bin/activate
pip install "dbt-core==1.12.7" "dbt-duckdb==1.11.1" "duckdb==1.5.6"
mkdir -p models/staging models/intermediate models/marts seedsdbt_project.yml sets a default materialisation for each folder: staging and intermediate models become views, which cost almost nothing to build, and marts become tables, which are fast to query. Lesson 3 explains the choice. profiles.yml defines two targets in the same DuckDB file: dev for your work and ci, which step 8 uses. threads: 1 makes dbt run one node at a time, so the order of the output is the same on every machine.
name: shop
version: "1.0.0"
profile: shop
models:
shop:
staging:
+materialized: view
intermediate:
+materialized: view
marts:
+materialized: tableshop:
target: dev
outputs:
dev:
type: duckdb
path: shop.duckdb
schema: dev
threads: 1
ci:
type: duckdb
path: shop.duckdb
schema: ci
threads: 1dbt debug23:35:24 Running with dbt=1.12.7
...
23:35:28 Connection test: [OK connection ok]
23:35:28 All checks passed!dbt debug checks that dbt can read both files, find the adapter and open the database. Its other lines show paths and versions on your machine.
03. Step 2: Load the raw tables
In production an ingestion tool would copy these tables from the shop's database into a raw schema. Here a short Python script plays that role. Look at the data before you model it: emails are not all lower case, order_date is text, the orders table calls the customer user_id, amounts are in cents, and order 102 has one failed and one successful payment.
"""Stand-in for an ingestion tool: writes three raw tables into shop.duckdb."""
import duckdb
con = duckdb.connect("shop.duckdb")
con.execute("CREATE SCHEMA IF NOT EXISTS raw")
con.execute("""
CREATE OR REPLACE TABLE raw.customers AS SELECT * FROM (VALUES
(1, 'Amara', 'Okafor', '[email protected]', 'NG'),
(2, 'Ben', 'Hughes', '[email protected]', 'GB'),
(3, 'Chloe', 'Martin', '[email protected]', 'FR'),
(4, 'Dev', 'Patel', '[email protected]', 'GB')
) AS t(id, first_name, last_name, email, country)""")
con.execute("""
CREATE OR REPLACE TABLE raw.orders AS SELECT * FROM (VALUES
(101, 1, '2026-03-02', 'shipped'),
(102, 2, '2026-03-02', 'shipped'),
(103, 1, '2026-03-05', 'returned'),
(104, 3, '2026-03-06', 'placed'),
(105, 2, '2026-03-09', 'shipped')
) AS t(id, user_id, order_date, status)""")
con.execute("""
CREATE OR REPLACE TABLE raw.payments AS SELECT * FROM (VALUES
(9001, 101, 'card', 4500, 'success'),
(9002, 102, 'card', 1999, 'failed'),
(9003, 102, 'voucher', 1999, 'success'),
(9004, 103, 'card', 3000, 'success'),
(9005, 105, 'card', 2500, 'success'),
(9006, 105, 'voucher', 500, 'success')
) AS t(id, order_id, payment_method, amount_cents, status)""")
for table in ["customers", "orders", "payments"]:
n = con.execute(f"SELECT count(*) FROM raw.{table}").fetchone()[0]
print(f"raw.{table}: {n} rows")python load_raw.pyraw.customers: 4 rows
raw.orders: 5 rows
raw.payments: 6 rows04. Step 3: Declare the sources and test them
A source declaration tells dbt that a table exists and that something outside dbt loads it. The file below declares a source called shop that lives in the schema raw, with three tables. Under each table you can list columns and data tests: queries that dbt runs against the data and that fail when they return rows. unique and not_null are two of the four tests built into dbt. Testing sources catches a broken load before any model reads it.
dbt reads every .yml file under models/; the leading underscore only sorts the file to the top of the folder. A small helper script prints one line per node from target/run_results.json, a file dbt writes after every command. It gives you a short, stable summary instead of the timed log.
sources:
- name: shop
schema: raw
tables:
- name: customers
columns:
- name: id
data_tests: [unique, not_null]
- name: orders
columns:
- name: id
data_tests: [unique, not_null]
- name: payments
columns:
- name: id
data_tests: [unique, not_null]"""Print the status and name of every node in dbt's last run, in run order."""
import json
with open("target/run_results.json") as f:
run = json.load(f)
for result in run["results"]:
kind, _, name = result["unique_id"].split(".")[:3]
print(f"{result['status']:<7} {kind:<5} {name}")dbt test --select "source:shop" --quiet
python results.pypass test source_not_null_shop_customers_id
pass test source_not_null_shop_orders_id
pass test source_not_null_shop_payments_id
pass test source_unique_shop_customers_id
pass test source_unique_shop_orders_id
pass test source_unique_shop_payments_id--quiet hides dbt's log and prints only errors, so an empty screen from dbt test means success. source:shop is a selector that matches every table of the shop source.
05. Step 4: One staging model per source table
Each staging model reads exactly one source table with source() and does only light work: rename columns to the names every later model will use, cast types, convert units and normalise values. There are no joins and no aggregations. From now on nothing else in the project reads the raw schema. If the shop renames user_id tomorrow, you change one line in stg_orders.sql.
In DuckDB, / returns a floating-point number even when you divide a decimal, so the result is cast to decimal(10, 2): an exact type with two decimal places, which keeps sums of money exact. The payment status becomes a boolean, is_successful, which reads more clearly in later filters.
select
id as customer_id,
first_name,
last_name,
lower(email) as email,
country as country_code
from {{ source('shop', 'customers') }}select
id as order_id,
user_id as customer_id,
cast(order_date as date) as order_date,
status
from {{ source('shop', 'orders') }}select
id as payment_id,
order_id,
payment_method,
cast(amount_cents / 100 as decimal(10, 2)) as amount,
status = 'success' as is_successful
from {{ source('shop', 'payments') }}Tests on staging models check the cleaned data. accepted_values fails if status holds a value outside the list. relationships fails if an order points at a customer that does not exist. In dbt 1.10.5 and later, a generic test's inputs go under arguments:.
models:
- name: stg_orders
columns:
- name: order_id
data_tests: [unique, not_null]
- name: status
data_tests:
- accepted_values:
arguments:
values: ['placed', 'shipped', 'returned']
- name: customer_id
data_tests:
- relationships:
arguments:
to: ref('stg_customers')
field: customer_id06. Step 5: An intermediate model, a seed and two marts
int_order_payments totals the successful payments per order. It reads stg_payments with ref(), so dbt knows it must build stg_payments first. Keeping this step in its own model means any future mart that needs "amount paid per order" reads the same definition. The seed maps country codes to names; it is the kind of small, rarely changing list that seeds are for.
select
order_id,
sum(amount) as amount_paid,
count(*) as payment_count
from {{ ref('stg_payments') }}
where is_successful
group by order_idcountry_code,country_name
FR,France
GB,United Kingdom
NG,Nigeriaselect
o.order_id,
o.customer_id,
o.order_date,
o.status,
coalesce(p.amount_paid, 0) as amount_paid
from {{ ref('stg_orders') }} as o
left join {{ ref('int_order_payments') }} as p using (order_id)select
c.customer_id,
c.first_name || ' ' || c.last_name as full_name,
n.country_name,
count(o.order_id) as order_count,
coalesce(sum(o.amount_paid), 0) as lifetime_paid
from {{ ref('stg_customers') }} as c
left join {{ ref('country_names') }} as n using (country_code)
left join {{ ref('fct_orders') }} as o using (customer_id)
group by alldim_customers reads fct_orders, a mart reading another mart. That is acceptable when the second mart really is built on the first one's grain; here it saves repeating the payment logic.
07. Step 6: Build and test everything with dbt build
dbt build loads seeds, builds models and runs tests in one pass, in graph order. Each model's tests run right after the model, and a failing test makes dbt skip everything downstream of it. dbt run, which lesson 3 uses, only builds models: it runs no tests, seeds or snapshots. Then query both marts.
dbt build --quiet
python results.py
dbt show --inline "select * from {{ ref('fct_orders') }} order by 1" --quiet
dbt show --inline "select * from {{ ref('dim_customers') }} order by 1" --quietsuccess seed country_names
pass test source_not_null_shop_customers_id
pass test source_not_null_shop_orders_id
pass test source_not_null_shop_payments_id
pass test source_unique_shop_customers_id
pass test source_unique_shop_orders_id
pass test source_unique_shop_payments_id
success model stg_customers
success model stg_orders
success model stg_payments
pass test accepted_values_stg_orders_status__placed__shipped__returned
pass test not_null_stg_orders_order_id
pass test relationships_stg_orders_customer_id__customer_id__ref_stg_customers_
pass test unique_stg_orders_order_id
success model int_order_payments
success model fct_orders
success model dim_customers
| order_id | customer_id | order_date | status | amount_paid |
| -------- | ----------- | ---------- | -------- | ----------- |
| 101 | 1 | 2026-03-02 | shipped | 45.00 |
| 102 | 2 | 2026-03-02 | shipped | 19.99 |
| 103 | 1 | 2026-03-05 | returned | 30.00 |
| 104 | 3 | 2026-03-06 | placed | 0.00 |
| 105 | 2 | 2026-03-09 | shipped | 30.00 |
| customer_id | full_name | country_name | order_count | lifetime_paid |
| ----------- | ------------ | -------------- | ----------- | ------------- |
| 1 | Amara Okafor | Nigeria | 2 | 75.00 |
| 2 | Ben Hughes | United Kingdom | 2 | 49.99 |
| 3 | Chloe Martin | France | 1 | 0.00 |
| 4 | Dev Patel | United Kingdom | 0 | 0.00 |Check the numbers by hand. Order 102 shows 19.99, not 39.98, because the failed card payment is filtered out in the intermediate model. Order 104 has no payment yet, so the left join gives NULL and coalesce turns it into 0. Dev Patel has no orders but still appears, because dim_customers starts from customers. The queries end with order by 1, which sorts by the first column: a table has no guaranteed row order, so sort before you compare results.
08. Step 7: Read the graph with dbt ls and manifest.json
dbt ls (short for list) prints the nodes a selector matches without running anything. +fct_orders means "fct_orders and all its ancestors"; stg_customers+ means "stg_customers and all its descendants". --output name prints short names, and --resource-type limits the kinds of node.
dbt ls --select +fct_orders --output name --quiet
echo "---"
dbt ls --select stg_customers+ --resource-type model --output name --quietfct_orders
int_order_payments
stg_orders
stg_payments
shop.orders
shop.payments
accepted_values_stg_orders_status__placed__shipped__returned
not_null_stg_orders_order_id
relationships_stg_orders_customer_id__customer_id__ref_stg_customers_
source_not_null_shop_orders_id
source_not_null_shop_payments_id
source_unique_shop_orders_id
source_unique_shop_payments_id
unique_stg_orders_order_id
---
dim_customers
stg_customersThe first list holds the two staging models, the intermediate model and two of the three sources, but not customers, which fct_orders never reads. It also holds the tests on those nodes. By default dbt adds a test when any node it tests is selected, which is why the relationships test appears even though stg_customers is not an ancestor. The second list shows the blast radius of a change to stg_customers: only dim_customers is downstream.
Behind dbt ls is target/manifest.json, a file dbt writes every time it parses the project. It describes every node and the edges between them. Other tools read it too: documentation sites, orchestrators and the CI job in lesson 5. parent_map lists each node's direct parents.
"""Read the dependency graph that dbt wrote to target/manifest.json."""
import json
with open("target/manifest.json") as f:
manifest = json.load(f)
for node in ["model.shop.fct_orders", "model.shop.dim_customers"]:
print(node)
for parent in manifest["parent_map"][node]:
print(" <-", parent)python lineage.pymodel.shop.fct_orders
<- model.shop.int_order_payments
<- model.shop.stg_orders
model.shop.dim_customers
<- model.shop.fct_orders
<- model.shop.stg_customers
<- seed.shop.country_namesCompare these edges with the sketch from the previous lesson. Each one exists because of a ref() call in the SQL, and dbt found it at parse time without running a query.
09. Step 8: What a hard-coded table name does
A common shortcut is to type the table name a model reads, because it is already there in dev. Change the from line of fct_orders.sql so it reads dev.stg_orders directly:
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
coalesce(p.amount_paid, 0) as amount_paid
from dev.stg_orders as o
left join {{ ref('int_order_payments') }} as p using (order_id)dbt ls --select +fct_orders --resource-type model --output name --quiet
dbt compile --select fct_orders --target ci --quietfct_orders
int_order_payments
stg_payments
select
o.order_id,
o.customer_id,
o.order_date,
o.status,
coalesce(p.amount_paid, 0) as amount_paid
from dev.stg_orders as o
left join "shop"."ci"."int_order_payments" as p using (order_id)Two things went wrong, and neither produced an error. stg_orders has vanished from the ancestors of fct_orders, so dbt no longer knows it must build stg_orders first; with several threads it could build fct_orders before its input. And the ci build now mixes environments: the payments come from ci, the orders from dev. A test run in CI would check your colleague's development data, not the change under review.
Put {{ ref('stg_orders') }} back in the from line and run dbt build --quiet to confirm the project is whole again.
10. Check your understanding
11. Apply it
Extend the project towards the practice project of this skill:
- Add a
raw.refundstable toload_raw.pyand to the source YAML, with tests on its key, then writestg_refundsfollowing the same rules as the other staging models. - Add refunds to
int_order_paymentsso thatfct_ordersgets anet_paidcolumn, and check order 105 by hand. - Add a
not_nulltest onfct_orders.amount_paidand anaccepted_valuestest onstg_payments.payment_method. - Run
dbt ls --select stg_payments+before and after your change and explain the difference.
12. Review prompt
Without looking back, explain in your own words:
- what a source declaration adds compared with naming
raw.ordersin a model; - the rules a staging model follows, and why only staging models read sources;
- what
+fct_ordersandstg_customers+select, and why tests appear in those lists; - what
manifest.jsoncontains and how dbt fillsparent_map; - the two silent problems a hard-coded table name caused in step 8.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.