0
0
DbtHow-ToBeginner ยท 3 min read

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 %}: Assigns value to variable_name.
  • variable_name can be any valid identifier.
  • value can 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 greeting
๐Ÿ’ป

Example

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 = true
Output
SELECT id, name, email FROM raw.customers WHERE active = true
โš ๏ธ

Common Pitfalls

Common mistakes when using set in dbt Jinja include:

  • Trying to use set inside {{ }} which is for expressions only; set must 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 col
๐Ÿ“Š

Quick Reference

UsageDescriptionExample
Set variableAssign a value to a variable{% set var = 'value' %}
Use variableInsert variable value in SQLSELECT '{{ var }}' AS col
Set listAssign a list to a variable{% set my_list = ['a', 'b'] %}
Use listLoop 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.