0
0
DbtHow-ToBeginner ยท 3 min read

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 users
Output
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

SyntaxDescription
{% 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.indexCurrent loop iteration starting at 1
loop.lastTrue 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.