How can you combine a for loop with a filter condition in dbt to generate SQL only for columns that start with 'user_'?
hard📝 Application Q9 of 15
dbt - Jinja in dbt
How can you combine a for loop with a filter condition in dbt to generate SQL only for columns that start with 'user_'?
A{% for col in columns if col.startswith('user_') %}{{ col }}, {% endfor %}
B{% for col in columns %}{% if col.startswith('user_') %}{{ col }}, {% endif %}{% endfor %}
C{% for col in columns %}{{ col if col.startswith('user_') else '' }}, {% endfor %}
D{% for col in columns %}FILTER {{ col }} WHERE col LIKE 'user_%'{% endfor %}
Step-by-Step Solution
Solution:
Step 1: Understand filtering inside for loops in dbt
Jinja does not support inline filters in for loops, so filtering must be done inside the loop with an if statement.
Step 2: Identify correct syntax for filtering
{% for col in columns %}{% if col.startswith('user_') %}{{ col }}, {% endif %}{% endfor %} uses an if condition inside the loop to output only matching columns.
Final Answer:
{% for col in columns %}{% if col.startswith('user_') %}{{ col }}, {% endif %}{% endfor %} -> Option B
Quick Check:
Filter inside loop with if condition [OK]
Quick Trick:Use if inside for loop to filter items in dbt [OK]
Common Mistakes:
MISTAKES
Trying to filter in the for loop declaration
Using inline if expressions incorrectly
Misusing SQL FILTER keyword inside Jinja loops
Master "Jinja in dbt" in dbt
9 interactive learning modes - each teaches the same concept differently