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 namedvariable_name.var('variable_name', default_value): Returnsdefault_valueif 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.ymlor 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
| Usage | Description |
|---|---|
| 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.yml | Set variables globally for your project |
| Pass via CLI | Override 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.