dbt Variables (vars)
In software engineering, you are taught never to "hardcode" magic numbers into your logic.
If you have a business rule stating that "All orders before January 1st, 2020 should be ignored," you should not type '2020-01-01' directly into 15 different .sql files. If the CEO suddenly decides the cut-off date is actually 2021, you have to find and replace that string across the entire codebase.
Instead, you define a Global Variable once, and reference it everywhere. In dbt, these are simply called vars.
Topics Covered
- What are
vars? - Defining Variables in
dbt_project.yml - Overriding Variables via CLI
1. What are vars?
A var in dbt is a globally accessible constant that you can reference inside any model, macro, or test using Jinja.
They are incredibly useful for defining:
- Global cut-off dates (e.g.,
event_start_date: '2023-01-01') - Tax rates (e.g.,
india_gst_rate: 0.18) - Marketing attribution windows (e.g.,
attribution_days: 14) - Boolean flags to toggle logic on or off (e.g.,
include_test_users: false)
2. Defining Variables in dbt_project.yml
To create a global variable, open your dbt_project.yml file and add a vars: block.
Note: The vars block should be at the same indentation level as models: and name:.
# dbt_project.yml
name: beems_retail
version: '1.0.0'
vars:
# Define the standard 18% GST rate for Indian transactions
india_gst_rate: 0.18
# Define the launch date of the new e-commerce app
app_launch_date: '2023-05-01'
# Should we include internal Beems employees in revenue reports?
include_internal_users: false
Once defined here, these variables become available to every single .sql file in your project.
3. Overriding Variables via the CLI
The true power of variables is that they can be overwritten dynamically at runtime without touching the code.
Let's assume the Finance team usually excludes internal employees (include_internal_users: false). But today, the CFO specifically asks for a special ad-hoc report that includes internal employees to audit employee discounts.
You do not need to change the dbt_project.yml file. You can override the variable directly from the terminal using the --vars flag!
# Run the finance models, but temporarily set the variable to true!
dbt run --select path:models/marts/finance --vars '{"include_internal_users": true}'
When dbt executes this run, it will replace the false value in the YAML file with true for this specific execution. When the pipeline runs again tomorrow on its normal schedule, it will revert back to false.
Summary
varsare global constants used to replace hardcoded "magic numbers" or strings in your SQL.- They are defined inside a
vars:block in yourdbt_project.ymlfile. - They are perfect for tax rates, start dates, and configuration flags.
- You can dynamically override them at runtime using the
--varsflag in the CLI.
(In the next section, we will look at how to actually use these variables inside your SQL code using the {{ var() }} function).