In this lesson, you will learn how to use the ref function in dbt to create dynamic dependencies between your models, ensuring dbt always understands the correct order to execute your transformation pipeline.
The Problem: Hardcoded Dependencies
When you build data pipelines, your models often stack on top of one another. For example, you might have a model that cleans raw customer data (stg_customers), which then feeds into a model that calculates lifetime value (fct_customer_ltv).
If you hardcode your SQL references by writing FROM my_database.my_schema.stg_customers, your pipeline becomes brittle. If you ever change your schema names or move to a different database environment (like switching from development to production), your code will break. Even worse, dbt won't know that fct_customer_ltv depends on stg_customers, meaning it might try to run the models in the wrong order.
The Solution: The ref Function
The ref function is the most important tool in your dbt toolkit. It tells dbt: "This model depends on the output of another model." By using {{ ref('model_name') }}, you replace hardcoded table names with a logical reference.
dbt uses these references to automatically build a Directed Acyclic Graph (DAG)—a map of all your models and their relationships. Because dbt understands this map, it will always run the upstream dependencies first.
Example
Instead of writing a hardcoded SQL path, you write your query like this:
-- models/fct_customer_ltv.sql
SELECT
customer_id,
SUM(order_amount) AS total_revenue
FROM {{ ref('stg_customers') }}
GROUP BY 1
When you execute dbt run, dbt looks at this ref call, identifies that stg_customers is an upstream model, and ensures it is materialized in your database before it attempts to build fct_customer_ltv. This makes your pipeline modular, portable, and self-documenting. You no longer need to worry about schema prefixes or execution order; dbt handles the plumbing for you.
Key Takeaway: The ref function decouples your SQL code from your physical database environment and automatically orchestrates your transformation pipeline by building a dependency graph.