0
0
DbtHow-ToBeginner ยท 3 min read

How to Use Vars in dbt: Simple Guide with Examples

In dbt, you use vars to pass dynamic values into your models or macros by defining them in your dbt_project.yml or via the command line. Access these variables inside your SQL or Jinja code with var('variable_name', default_value) to customize behavior without changing code.
๐Ÿ“

Syntax

The vars feature in dbt lets you define variables that can be accessed in your models or macros. You define variables as key-value pairs in dbt_project.yml or pass them via the command line using --vars. Inside your SQL or Jinja code, use var('variable_name', default_value) to get the variable's value or a default if not set.

  • var('variable_name'): Accesses the variable named variable_name.
  • var('variable_name', default_value): Returns default_value if the variable is not defined.
sql
models/my_model.sql

-- Access a variable named 'start_date'
select * from my_table
where date >= '{{ var("start_date", "2023-01-01") }}'
๐Ÿ’ป

Example

This example shows how to define a variable in dbt_project.yml and use it in a model to filter data dynamically.

yaml + sql
# dbt_project.yml
vars:
  start_date: '2023-05-01'

-- models/filter_by_date.sql
select * from sales
where order_date >= '{{ var("start_date") }}'
Output
This model will select all sales records where <code>order_date</code> is on or after 2023-05-01, using the <code>start_date</code> variable defined in <code>dbt_project.yml</code>.
โš ๏ธ

Common Pitfalls

Common mistakes when using vars in dbt include:

  • Not defining the variable in dbt_project.yml or passing it via command line, causing errors or unexpected defaults.
  • Forgetting to provide a default value in var(), which can cause runtime errors if the variable is missing.
  • Using incorrect variable names or typos inside var().

Always test your models with and without variables set to ensure graceful fallback.

sql
-- Wrong usage (no default, variable not set)
select * from my_table
where date >= '{{ var("missing_var") }}'

-- Correct usage with default
select * from my_table
where date >= '{{ var("missing_var", "2023-01-01") }}'
๐Ÿ“Š

Quick Reference

UsageDescription
var('name')Get the value of variable 'name', error if not set
var('name', 'default')Get 'name' or return 'default' if not set
Define in dbt_project.ymlSet variables globally for your project
Pass via CLIOverride variables when running dbt with --vars '{"name": "value"}'
โœ…

Key Takeaways

Use var('name', default) to safely access variables in dbt models and macros.
Define variables in dbt_project.yml or pass them via the command line with --vars.
Always provide a default value in var() to avoid runtime errors.
Check variable names carefully to prevent typos and unexpected behavior.
Variables help make your dbt models flexible and reusable without changing code.