How to Use ref Function in dbt: Simple Guide
In dbt, use the
ref function to reference other models by their name, which helps dbt understand dependencies and build models in the right order. Simply write ref('model_name') inside your SQL code to link to another model.Syntax
The ref function takes the name of another model as a string and returns a reference to that model's table or view in your database. This helps dbt know the order to run models and manage dependencies automatically.
- ref('model_name'): The model_name is the exact name of the model you want to reference.
sql
select * from {{ ref('my_model') }}
Example
This example shows how to use ref to select data from another model called customers. It ensures dbt builds the customers model first, then runs this model.
sql
select id, name, email from {{ ref('customers') }} where active = true
Output
This SQL will select active customers from the 'customers' model's table or view in the database.
Common Pitfalls
Common mistakes when using ref include:
- Using
refwith a model name that does not exist causes build errors. - Passing variables or expressions instead of a string literal to
refis not allowed. - Using raw table names instead of
refbreaks dependency tracking.
Always use ref with exact model names as strings to avoid these issues.
sql
/* Wrong way - using variable */ {% set model_name = 'customers' %} select * from {{ ref(model_name) }} /* Right way - use string literal */ select * from {{ ref('customers') }}
Quick Reference
| Usage | Description |
|---|---|
| ref('model_name') | References another dbt model by name |
| Used inside {{ }} | Must be inside Jinja templating brackets |
| Returns table/view name | Outputs the correct database object name |
| Tracks dependencies | Helps dbt build models in correct order |
| Only string literals | Model name must be a fixed string |
Key Takeaways
Use ref('model_name') to reference other models and manage dependencies in dbt.
Always pass the model name as a string literal inside ref().
ref helps dbt build models in the right order automatically.
Avoid using variables or raw table names instead of ref for dependencies.
ref returns the correct database table or view name for the referenced model.