0
0
DbtHow-ToBeginner ยท 3 min read

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 ref with a model name that does not exist causes build errors.
  • Passing variables or expressions instead of a string literal to ref is not allowed.
  • Using raw table names instead of ref breaks 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

UsageDescription
ref('model_name')References another dbt model by name
Used inside {{ }}Must be inside Jinja templating brackets
Returns table/view nameOutputs the correct database object name
Tracks dependenciesHelps dbt build models in correct order
Only string literalsModel 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.