For loops for dynamic SQL
📖 Scenario: You work as a data analyst using dbt to build SQL models. You want to create a dynamic SQL query that selects sales data for multiple regions without repeating code.
🎯 Goal: Build a dbt model using a for loop in Jinja to dynamically generate SQL code for multiple regions.
📋 What You'll Learn
Create a list variable called
regions with the values 'north', 'south', and 'east'.Create a variable called
sales_threshold and set it to 1000.Use a
for loop with the variable region to iterate over regions and generate a SQL SELECT statement for each region.Print the final SQL query string that combines all region queries with
UNION ALL.💡 Why This Matters
🌍 Real World
Data analysts often need to write SQL queries that repeat similar logic for different categories or regions. Using loops helps avoid repetitive code and makes maintenance easier.
💼 Career
Knowing how to generate dynamic SQL with loops is useful for dbt developers and data engineers who build scalable and maintainable data transformation pipelines.
Progress0 / 4 steps