How to Use set in Jinja for dbt: Syntax and Examples
In dbt, use the
{% set variable_name = value %} syntax in Jinja to assign values to variables for reuse in your SQL models or macros. This helps you write cleaner, dynamic SQL by storing expressions or values in variables.Syntax
The set statement in Jinja assigns a value to a variable that you can use later in your dbt model or macro. It uses the format:
{% set variable_name = value %}: Assignsvaluetovariable_name.variable_namecan be any valid identifier.valuecan be a string, number, list, or expression.
You can then use {{ variable_name }} to insert the variable's value.
jinja
{% set my_var = 'hello' %}
SELECT '{{ my_var }}' AS greetingExample
This example shows how to set a variable for a table name and use it in a SQL query inside a dbt model.
jinja
{% set source_table = 'raw.customers' %}
SELECT
id,
name,
email
FROM {{ source_table }}
WHERE active = trueOutput
SELECT
id,
name,
email
FROM raw.customers
WHERE active = true
Common Pitfalls
Common mistakes when using set in dbt Jinja include:
- Trying to use
setinside{{ }}which is for expressions only;setmust be inside{% %}. - Forgetting to use double curly braces
{{ variable }}to output the variable's value. - Assigning complex SQL directly without quotes or proper formatting, causing syntax errors.
jinja
{# Wrong usage: set inside expression tags #}
{{ set my_var = 'value' }}
{# Correct usage: set inside statement tags #}
{% set my_var = 'value' %}
SELECT '{{ my_var }}' AS colQuick Reference
| Usage | Description | Example |
|---|---|---|
| Set variable | Assign a value to a variable | {% set var = 'value' %} |
| Use variable | Insert variable value in SQL | SELECT '{{ var }}' AS col |
| Set list | Assign a list to a variable | {% set my_list = ['a', 'b'] %} |
| Use list | Loop over list items | {% for item in my_list %}{{ item }} {% endfor %} |
Key Takeaways
Use {% set variable = value %} to assign variables in dbt Jinja templates.
Always use {{ variable }} to output the variable's value in your SQL code.
Set statements must be inside {% %} tags, not {{ }}.
Variables can hold strings, numbers, lists, or expressions for dynamic SQL.
Using set helps keep your dbt models clean and easier to maintain.