Bird
0
0

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:
  1. 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.
  2. 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.
  3. Final Answer:

    {% for col in columns %}{% if col.startswith('user_') %}{{ col }}, {% endif %}{% endfor %} -> Option B
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More dbt Quizzes