Skip to content
Bronze 5 min read · source(), Staging 2 practice problems ↓

Sources and staging models

Raw tables are loaded into the warehouse by other tools. dbt does not build them, but it should know about them. This lesson shows how to declare sources, check their freshness, and build the first layer of models on top: staging.

Pipelines in production · dbt · Bronze · Building models, lesson 1 of 4

Read first: A dbt project, file by file (skip if you know it)

In plain words first

Groceries arrive from different suppliers in different packaging. The first job in the kitchen is to unpack and wash them the same way, so every recipe after that starts from clean, consistent ingredients.

Sources are the deliveries, declared so dbt knows where they come from; staging modelsmodel: A SELECT statement in a .sql file. dbt runs it and saves the result in the warehouse as a table or view named after the file. Learn more → are the washing and unpacking: rename, cast, nothing more.

Declaring sources

Raw tables are loaded by other tools, so dbt does not build them. You declare them once in YAML, and models read them with source('<source name>', '<table name>').

YAML · models/staging/billing/_billing__sources.yml
sources:
  - name: billing             # the name used in source('billing', ...)
    database: raw
    schema: billing_prod      # where the loader writes
    loaded_at_field: _ingested_at
    freshness:
      warn_after: {count: 6, period: hour}
      error_after: {count: 24, period: hour}
    tables:
      - name: invoices
        columns:
          - name: id
            data_tests: [unique, not_null]
      - name: charges
      - name: price_list
        freshness: null       # changed by hand a few times a year
dbt · models/staging/billing/stg_billing__invoices.sql
select * from {{ source('billing', 'invoices') }}

Compiles to

select * from raw.billing_prod.invoices

The compiled SQL is the same as typing the name, so why bother? Because source() puts the raw table into the DAGDAG: The graph of models that ref() calls create. dbt uses it to build models in dependency order. Learn more →: lineage graphs start at it, dbt build --select source:billing+ builds everything downstream of it, the schema is changed in one YAML line when the loader moves, and tests and freshness checks attach to it.

Source freshness

dbt source freshness queries max(_ingested_at) for each source table and compares it to now. If the loader stopped six hours ago you get a warning; after a day, an error. Run it at the start of a production job so stale data stops the pipeline before it reaches dashboards.

Shell · Freshness in a job
dbt source freshness                        # check, write target/sources.json
# rebuild only what new data feeds (needs --state)
dbt build --select source_status:fresher+

What a staging model does

A staging model has one source table as input and produces a clean version of it. The same few operations, every time:

Rename

id to invoice_id, acct to account_id: consistent names across sources.

Cast

Strings to dates and numbers, so marts never cast again.

Fix units

Cents to dollars, epoch seconds to timestamps, lower-cased emails.

Filter junk

Test rows, soft-deleted rows, rows without a key, with null-safe conditions.

Deduplicate

Keep the latest version of each key from change-data feeds.

Nothing else

No joins, no aggregation: those happen downstream.
dbt · models/staging/billing/stg_billing__invoices.sql
with source as (
    select * from {{ source('billing', 'invoices') }}
),

cleaned as (
    select
        id                                  as invoice_id,
        acct                                as account_id,
        to_timestamp(issued_epoch)          as issued_at,
        upper(currency_code)                as currency,
        total_minor_units / 100.0           as total
    from source
    where coalesce(is_sandbox, false) = false   -- rows with a null flag are real
)

select * from cleaned
Watch out: where is_sandbox = false silently drops rows where is_sandbox is null, because null = false is not true. Decide what null means and write it down, as coalesce does above.

Deduplicating change data

Loaders that capture changes (CDC) append a new row each time a record changes, so the raw table has several versions of each account. The staging model keeps the latest one:

dbt · models/staging/app/stg_app__accounts.sql
select
    account_id,
    plan_code,
    seats,
    changed_at
from {{ source('app', 'accounts_changelog') }}
qualify 1 = row_number() over (
    partition by account_id
    order by changed_at desc, _ingested_at desc   -- tie-breaker for equal changed_at
)

qualify filters on a window functionwindow function: A function that computes a value for each row from a group of related rows (its window), without collapsing them like groupBy does. Learn more → without a subquery (Snowflake, BigQuery, Databricks and DuckDB support it; elsewhere wrap the query and filter on the row number). The second sort column matters: without it, two versions with the same changed_at are picked at random, and the result changes between runs.

Common mistakes

  • Reading a source from a mart — Every model that calls source() directly is another place to fix when the raw table changes.
  • Deduplicating without a tie-breaker — row_number over a column with ties returns either row, so results differ between runs.
  • Freshness on tables loaded rarely — A weekly table always looks stale against a 6-hour rule. Set freshness per table, or null.

Key takeaways

  • Declare raw tables in YAML and read them with source().
  • dbt source freshness turns a stalled loader into a warning or error.
  • Staging models rename, cast, clean and deduplicate one source table, and nothing more.
  • Null-safe filters and deterministic tie-breakers keep staging correct.

Interview prep

THE QUESTION

"Why use source() instead of writing the raw table name?"

source() compiles to the same name, but it registers the raw table in the DAG. That gives lineage from raw data to dashboards, selection such as source:shop+, one place to change the database or schema, and a place to attach tests and freshness checks. Staging models are the only ones that call it, so a change in a raw table is fixed once.

Avoid: "source() is just a shortcut for the table name". Mention lineage, selection, freshness and the single place to change it.

Follow-ups · answer out loud, then open

Follow-up"How does dbt know a source is stale?"
dbt source freshness computes max(loaded_at_field) per table and compares it with warn_after and error_after. Running it first in a production job stops the build when a loader has stalled.
Scenario"A CDC source has several rows per account. How do you stage it?"
Keep the latest version per key with row_number() over the key, ordered by the change timestamp descending, plus a tie-breaker (such as the ingestion time) so the result is deterministic, and handle delete markers if the feed has them. Then put unique and not_null tests on the key.
Trap"Staging models should join in the lookup tables they need."
Staging is one model per source table: rename, cast, clean. Joins go in intermediate models or marts, so each source is cleaned once and reused.

Check yourself

3 questions

What does {{ source('billing', 'invoices') }} compile to?

Show the answer

The fully qualified raw table name from the source YAML. source() resolves to database.schema.table as declared.

Which belongs in a staging model?

Show the answer

Casting issued_epoch to a timestamp and renaming id to invoice_id. Staging is rename, cast, clean; joins and aggregation come later.

A filter is written as where is_deleted = false. What happens to rows where is_deleted is null?

Show the answer

They are dropped. null = false is unknown, and WHERE keeps only true.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Building models · lesson 2 of 4 · 5 min read
ref() and the DAG
How ref() builds the dependency graph, picks the right schema per environment, and drives node selection.

Related lessons

Previous: A dbt project, file by file

Primary sources: Add sources to your DAG · How we structure: staging