0
0
dbtdata~5 mins

ref() function for model dependencies in dbt

Choose your learning style9 modes available
Introduction

The ref() function helps connect different data models in dbt. It makes sure models run in the right order and use the correct data.

When you want one data model to use the output of another model.
When you need dbt to understand the order to build your models.
When you want to avoid hardcoding table names and keep your project flexible.
When you want to easily track dependencies between models in your project.
Syntax
dbt
select * from {{ ref('model_name') }}

The ref() function takes the name of another model as a string.

It returns the correct table name or view for that model, depending on your dbt setup.

Examples
This selects all data from the customers model.
dbt
select * from {{ ref('customers') }}
This selects specific columns from the orders model.
dbt
select order_id, customer_id from {{ ref('orders') }}
This uses ref() inside a common table expression (CTE) to filter recent orders.
dbt
with recent_orders as (
  select * from {{ ref('orders') }} where order_date > '2024-01-01'
)
select * from recent_orders
Sample Program

This example shows three models. The customer_orders.sql model uses ref() to get data from customers and orders. It joins them to list recent orders with customer names.

dbt
/* Model: customers.sql */
select
  id as customer_id,
  name
from raw.customers

/* Model: orders.sql */
select
  id as order_id,
  customer_id,
  order_date
from raw.orders

/* Model: customer_orders.sql */
select
  c.customer_id,
  c.name,
  o.order_id,
  o.order_date
from {{ ref('customers') }} c
join {{ ref('orders') }} o on c.customer_id = o.customer_id
where o.order_date > '2024-01-01'
order by o.order_date desc
OutputSuccess
Important Notes

Always use ref() instead of hardcoding table names to keep your project flexible.

dbt uses ref() to build a dependency graph and run models in the right order.

If you rename a model, ref() helps avoid errors by updating references automatically.

Summary

ref() links models so dbt knows their order and dependencies.

It helps avoid hardcoding table names and keeps your project flexible.

Use ref() whenever you want one model to use another model's data.