What if you could write one query that magically creates many for you?
Why For loops for dynamic SQL in dbt? - Purpose & Use Cases
Imagine you have to write SQL queries for each month of the year manually. You copy and paste the same query 12 times, changing only the month value each time.
This manual method is slow and boring. It's easy to make mistakes like typos or forgetting to update a month. If you want to add more months or change the query, you must edit every copy again.
Using for loops for dynamic SQL lets you write one loop that automatically creates all the monthly queries. This saves time, reduces errors, and makes your code easy to update.
SELECT * FROM sales WHERE month = 'January'; SELECT * FROM sales WHERE month = 'February'; -- repeated for each month
{% set months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] %}
{% for month in months %}
SELECT * FROM sales WHERE month = '{{ month }}';
{% endfor %}You can generate many SQL queries dynamically with just a few lines of code, making your work faster and more reliable.
A data analyst uses a for loop in dbt to create monthly sales reports automatically, instead of writing separate queries for each month.
Manual SQL repetition is slow and error-prone.
For loops automate query generation dynamically.
This approach saves time and reduces mistakes.