The ref() function helps connect different data models in dbt. It makes sure models run in the right order and use the correct data.
ref() function for model dependencies in 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.
customers model.select * from {{ ref('customers') }}
orders model.select order_id, customer_id from {{ ref('orders') }}
ref() inside a common table expression (CTE) to filter recent orders.with recent_orders as ( select * from {{ ref('orders') }} where order_date > '2024-01-01' ) select * from recent_orders
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.
/* 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
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.
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.