Search⌘ K
AI Features

Iterations

Explore how to use Jinja for loops to iterate through lists, dictionaries, and ranges in dbt models. Understand loop variables, conditional logic inside loops, and nested loops to build flexible and reusable SQL queries with dynamic data.

The for loops

A for loop is a control structure that allows us to iterate over a collection (such as a list, a dictionary, or even a string). The for loops are especially useful when we want to apply the same type of logic to a subset of fields.

Iterating through a list

Jinja allows us to iterate using a for statement.

Python
{% for name in ["Pablo", "Alvaro", "Laura"] %}
{{ name }}
{% endfor %}

The syntax is as follows:

  • In the opening tag, we name the loop variable (which will store the value of each iteration) and specify which object we want to iterate in.

  • In the body of the loop (after the opening tag and before the closing tag), we can use our loop variable.

  • We end the loop with a closing tag. ... ... ...