How to Use For Loop in Jinja with dbt: Simple Guide
In dbt, you use a
for loop in Jinja by writing {% for item in list %}...{% endfor %} to repeat code blocks dynamically. This helps generate SQL code based on lists or dictionaries inside your dbt models or macros.Syntax
The for loop in Jinja starts with {% for variable in sequence %} and ends with {% endfor %}. Inside the loop, you can use the variable to access each item in the sequence.
- variable: name for each item in the loop
- sequence: list or dictionary to loop over
- {% endfor %}: marks the end of the loop
jinja
{% for item in my_list %}
-- use {{ item }} here
{% endfor %}Example
This example shows how to loop over a list of column names to select them dynamically in a dbt model using Jinja.
jinja
{% set columns = ['id', 'name', 'email'] %}
select
{% for col in columns %} {{ col }}{% if not loop.last %}, {% endif %}
{% endfor %}
from usersOutput
select
id, name, email
from users
Common Pitfalls
Common mistakes when using for loops in Jinja with dbt include:
- Forgetting to close the loop with
{% endfor %}. - Not handling commas or separators properly, which can cause invalid SQL.
- Using
{{ }}instead of{% %}for control statements like loops.
jinja
{% for col in columns %}
{{ col }}
{% endfor %} -- Missing commas between columns
-- Correct way:
{% for col in columns %}{{ col }}{% if not loop.last %}, {% endif %}{% endfor %}Quick Reference
| Syntax | Description |
|---|---|
| {% for item in list %} ... {% endfor %} | Loop over each item in a list or sequence |
| {{ variable }} | Print the value of a variable inside the loop |
| loop.index | Current loop iteration starting at 1 |
| loop.last | True if current item is the last in the loop |
| {% if condition %} ... {% endif %} | Conditional logic inside loops |
Key Takeaways
Use {% for item in list %} ... {% endfor %} to loop in Jinja within dbt.
Remember to close loops with {% endfor %} to avoid syntax errors.
Use loop.last to handle separators like commas correctly in SQL.
Use {% %} for control flow and {{ }} to print variables inside loops.
For loops help generate dynamic SQL code based on lists or dictionaries.