ref() and the DAG
In dbt, models refer to each other with ref() instead of table names. That one function lets dbt work out the build order, build into the right schema in every environment, and draw your pipeline's lineage. This lesson shows how.
Pipelines in production · dbt · Bronze · Building models, lesson 2 of 4
On this page
Read first: Sources and staging models (skip if you know it)
In plain words first
A recipe that says "use the sauce from recipe 12" instead of "use the sauce in the blue pot" still works when the pots move, and tells the cook that recipe 12 must be made first.
ref() is "the sauce from recipe 12": dbt learns the dependency, builds things in order, and fills in the real table name for the environment.
What ref() does
{{ ref('stg_invoices') }} does two things. At parse time it records an edge in the graph: this modelmodel: 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 → depends on stg_invoices. At compile time it becomes the full name of the relation stg_invoices was built into for the current target.
select invoice_id, total from {{ ref('stg_invoices') }}
Compiles to
-- dbt run (target dev) select invoice_id, total from analytics.dbt_alice.stg_invoices -- dbt run --target prod select invoice_id, total from analytics.analytics.stg_invoices
This is why developers can build the whole project in their own schema without touching production: every reference follows the target. A hard-coded analytics.stg_invoices would read production data from a dev build, and dbt would not know to build it first.
The DAG
-
sourcesource: A raw table loaded by another tool, declared in YAML so models can select from it with source() and dbt can test it and check its freshness. Learn more →
billing.invoices
-
staging
stg_invoices
-
intermediate
int_invoice_charges
-
mart
fct_invoices
-
mart
dim_accounts
dbt sorts the graph and starts every model whose parents are done, up to threads at once. Cycles are an error at parse time: if A refs B and B refs A, dbt refuses to run. With dbt build, each model's tests run right after it, and if a test fails, everything downstream of that model is skipped, so bad data does not spread.
Selecting part of the graph
| Selector | Builds |
|---|---|
| fct_invoices | Only fct_invoices |
| +fct_invoices | fct_invoices and everything upstream of it |
| fct_invoices+ | fct_invoices and everything downstream |
| 1+fct_invoices | fct_invoices and its direct parents only |
| @stg_invoices | stg_invoices, its descendants, and all ancestors of those descendants |
| tag:nightly | Models tagged nightly |
| path:models/marts | Everything in a folder |
| source:billing+ | Everything that reads the billing source |
| state:modified+ | Changed models and their descendants (see Slim CIslim CI: Building and testing only the models a pull request changed (and those downstream), found by comparing with the production manifest. Learn more →) |
dbt build --select stg_invoices+ # rebuild what a staging model feeds dbt run --select +fct_invoices --exclude tag:slow # a mart, its parents, not slow dbt ls --select @stg_invoices # preview a selection, run nothing
Use @ when the children of a model also need other parents that are not built yet, for example on a fresh dev schema: + alone would build the children against missing tables.
Building a mart from refs
Marts join staging modelsstaging model: The first layer of models: one per source table, renaming and casting columns, with no joins or business logic. Learn more →. The classic bug is fan-out: joining invoices to charges gives one row per charge, and summing invoice totals after the join double counts invoices that were paid in two charges. Aggregate the many side to the grain you need before joining.
with play_stats as ( -- one row per account before the join select account_id, count(*) as total_plays, count(distinct track_id) as distinct_tracks, max(played_at) as last_played_at from {{ ref('stg_plays') }} group by account_id ) select a.account_id, a.plan_code, coalesce(p.total_plays, 0) as total_plays, -- accounts that never played coalesce(p.distinct_tracks, 0) as distinct_tracks, p.last_played_at from {{ ref('stg_accounts') }} as a left join play_stats as p on p.account_id = a.account_id
A left join keeps accounts that never played anything, and coalesce turns their missing counts into 0, which is what "number of plays" should say. Add a unique test on account_id: if a later change causes fan-out, the test fails before anyone reads the table.
Common mistakes
- Hard-coding a schema instead of ref() — Dev builds read production, and dbt does not know the build order.
- Joining before aggregating — Fan-out inflates sums and counts. Aggregate the many side to the target grain first.
- Using + on a fresh schema — Children may need other parents that do not exist yet. Use @ or build upstream first.
Key takeaways
- ref() is both a dependency edge and an environment-aware table name.
- dbt runs the DAG in order, in parallel up to threads, and skips descendants of failed tests in dbt build.
- Graph operators (+, @, n+) and methods (tag:, path:, source:, state:) select what runs.
- Aggregate to the target grain before joining to avoid fan-out, and test the grain with unique.
Interview prep
THE QUESTION
"What does ref() do, and why not just write the table name?"
+model or state:modified+. With dbt build, a failing test on a model skips its descendants.Avoid: "ref() returns the table name". It also creates the dependency and switches with the target.
Follow-ups · answer out loud, then open
Follow-up"What is the difference between +model and @model?"
+model builds the model and all its ancestors. @model builds the model, all its descendants, and all ancestors of those descendants, which is what a fresh schema needs before building children that have other parents.Scenario"After a change, a mart's revenue doubled for some accounts. Where do you look?"
Trap"Two models can ref each other if the logic needs it."
Check yourself
3 questionsWhat does dbt run --select +dim_accounts build?
Show the answer
dim_accounts and all its ancestors. A leading + means upstream.
In dbt build, a unique test on stg_invoices fails. What happens to fct_invoices, which refs it?
Show the answer
It is skipped. dbt build skips the descendants of a node whose test failed.
Invoices are joined to charges, then sum(invoice_total) is taken per account. What is wrong?
Show the answer
Invoices paid in several charges are counted several times. The join fans out to one row per charge.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Building models · lesson 3 of 4 · 5 min readMaterializations
View, table, ephemeral, incremental and materialized view: what each builds and when to pick it.
Related lessons
Previous: Sources and staging models
Primary sources: ref · Node selection syntax