Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 30 min · revision 2

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

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.

Folder layout at the end of the lab
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.sql

02. Step 1: Install dbt and create the project files

Terminal
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 seeds

dbt_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.

YAML · dbt_project.yml
name: shop
version: "1.0.0"
profile: shop

models:
  shop:
    staging:
      +materialized: view
    intermediate:
      +materialized: view
    marts:
      +materialized: table
YAML · profiles.yml
shop:
  target: dev
  outputs:
    dev:
      type: duckdb
      path: shop.duckdb
      schema: dev
      threads: 1
    ci:
      type: duckdb
      path: shop.duckdb
      schema: ci
      threads: 1
Terminal
dbt debug
Illustrative output (excerpt)
23: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.

Python · load_raw.py
"""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")
Terminal
python load_raw.py
Expected output
raw.customers: 4 rows
raw.orders: 5 rows
raw.payments: 6 rows

04. 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.

YAML · models/staging/_sources.yml
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]
Python · results.py
"""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}")
Terminal
dbt test --select "source:shop" --quiet
python results.py
Expected output
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

--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.

SQL · models/staging/stg_customers.sql
select
    id as customer_id,
    first_name,
    last_name,
    lower(email) as email,
    country as country_code
from {{ source('shop', 'customers') }}
SQL · models/staging/stg_orders.sql
select
    id as order_id,
    user_id as customer_id,
    cast(order_date as date) as order_date,
    status
from {{ source('shop', 'orders') }}
SQL · models/staging/stg_payments.sql
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:.

YAML · models/staging/_staging.yml
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_id

06. 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.

SQL · models/intermediate/int_order_payments.sql
select
    order_id,
    sum(amount) as amount_paid,
    count(*) as payment_count
from {{ ref('stg_payments') }}
where is_successful
group by order_id
CSV · seeds/country_names.csv
country_code,country_name
FR,France
GB,United Kingdom
NG,Nigeria
SQL · models/marts/fct_orders.sql
select
    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)
SQL · models/marts/dim_customers.sql
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 all

dim_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.

Terminal
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" --quiet
Expected output
success 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.

Terminal
dbt ls --select +fct_orders --output name --quiet
echo "---"
dbt ls --select stg_customers+ --resource-type model --output name --quiet
Expected output
fct_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_customers

The 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.

Python · lineage.py
"""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)
Terminal
python lineage.py
Expected output
model.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_names

Compare 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:

SQL · models/marts/fct_orders.sql
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)
Terminal
dbt ls --select +fct_orders --resource-type model --output name --quiet
dbt compile --select fct_orders --target ci --quiet
Expected output
fct_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

Practice check · 3 questions

Sources, tests and the graph

Each question changes one detail of the lab. Pick the best answer.

Q1. The ingestion team moves the three raw tables from schema `raw` to a new schema `landing`. What is the smallest change that keeps the project working?
Q2. Why does `dbt ls --select +fct_orders` list the `relationships` test on `stg_orders.customer_id`, although `stg_customers` is not an ancestor of `fct_orders`?
Q3. A teammate deletes `int_order_payments.sql` but leaves `fct_orders.sql` unchanged. What happens on the next `dbt build`?
Practice only: not graded, not saved, not evidence.

11. Apply it

Extend the project towards the practice project of this skill:

  1. Add a raw.refunds table to load_raw.py and to the source YAML, with tests on its key, then write stg_refunds following the same rules as the other staging models.
  2. Add refunds to int_order_payments so that fct_orders gets a net_paid column, and check order 105 by hand.
  3. Add a not_null test on fct_orders.amount_paid and an accepted_values test on stg_payments.payment_method.
  4. 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.orders in a model;
  • the rules a staging model follows, and why only staging models read sources;
  • what +fct_orders and stg_customers+ select, and why tests appear in those lists;
  • what manifest.json contains and how dbt fills parent_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.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check