0
0
DbtHow-ToBeginner ยท 4 min read

How to Use Variables in dbt: Syntax and Examples

In dbt, you use var() to access variables defined in your dbt_project.yml or passed at runtime. Use {{ var('variable_name', 'default_value') }} in your SQL or Jinja code to insert the variable's value, with an optional default if the variable is not set.
๐Ÿ“

Syntax

The var() function in dbt is used to retrieve the value of a variable. It takes two arguments: the variable name as a string, and an optional default value if the variable is not defined.

  • var('variable_name'): Returns the value of variable_name.
  • var('variable_name', 'default_value'): Returns the value of variable_name or default_value if not set.
jinja
{{ var('my_variable', 'default') }}
๐Ÿ’ป

Example

This example shows how to use a variable in a dbt model SQL file to filter data based on a variable passed at runtime or set in dbt_project.yml.

sql
-- models/example_model.sql
SELECT *
FROM {{ ref('my_source_table') }}
WHERE status = '{{ var("status_filter", "active") }}'
Output
This query selects all rows from 'my_source_table' where the 'status' column matches the value of the 'status_filter' variable or 'active' if not set.
โš ๏ธ

Common Pitfalls

Common mistakes when using variables in dbt include:

  • Not defining the variable in dbt_project.yml or passing it at runtime, causing errors if no default is provided.
  • Forgetting to wrap the variable in quotes when used inside SQL strings, leading to syntax errors.
  • Using variables for complex logic instead of Jinja macros, which can be more appropriate.
sql
-- Wrong usage (missing quotes):
SELECT * FROM table WHERE status = {{ var('status_filter') }}

-- Correct usage:
SELECT * FROM table WHERE status = '{{ var("status_filter", "active") }}'
๐Ÿ“Š

Quick Reference

UsageDescription
{{ var('name') }}Get variable 'name' value, error if not set
{{ var('name', 'default') }}Get variable 'name' or use 'default' if not set
Define in dbt_project.ymlSet variables globally for your project
Pass at runtimeOverride variables using --vars flag
โœ…

Key Takeaways

Use {{ var('variable_name', 'default') }} to safely access variables in dbt.
Always provide a default value or define the variable to avoid errors.
Wrap variables in quotes when used inside SQL strings to prevent syntax errors.
Define variables in dbt_project.yml or pass them at runtime with --vars.
Use variables for simple values; use macros for complex logic.