Challenge - 5 Problems
Dynamic SQL Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a dbt for loop generating SQL columns
What is the output SQL snippet generated by this dbt Jinja for loop?
{% raw %}{% for col in ['id', 'name', 'age'] %}
{{ col }} AS {{ col }}_alias{% if not loop.last %}, {% endif %}
{% endfor %}{% endraw %}dbt
{% for col in ['id', 'name', 'age'] %}
{{ col }} AS {{ col }}_alias{% if not loop.last %}, {% endif %}
{% endfor %}Attempts:
2 left
💡 Hint
Look at how commas are added only between items, not after the last one.
✗ Incorrect
The for loop iterates over the list and adds a comma only if the current item is not the last. This creates a comma-separated list of column aliases.
❓ data_output
intermediate1:30remaining
Number of columns generated by a dynamic for loop in dbt
Given this dbt for loop generating SQL columns from a list of 5 column names, how many columns will be generated?
{% raw %}{% for col in ['a', 'b', 'c', 'd', 'e'] %}
{{ col }} AS {{ col }}_alias{% if not loop.last %}, {% endif %}
{% endfor %}{% endraw %}dbt
{% for col in ['a', 'b', 'c', 'd', 'e'] %}
{{ col }} AS {{ col }}_alias{% if not loop.last %}, {% endif %}
{% endfor %}Attempts:
2 left
💡 Hint
Count the items in the list.
✗ Incorrect
The loop runs once for each item in the list, so it generates 5 columns.
🔧 Debug
advanced2:00remaining
Identify the error in this dbt for loop for dynamic SQL
What error will this dbt Jinja code produce when rendering?
Assume
{% raw %}{% for col in columns %}
{{ col }} AS {{ col }}_alias,
{% endfor %}{% endraw %}Assume
columns = ['x', 'y', 'z'].dbt
{% for col in columns %}
{{ col }} AS {{ col }}_alias,
{% endfor %}Attempts:
2 left
💡 Hint
Check how commas are placed after each column.
✗ Incorrect
The loop adds a comma after every column including the last one, which causes a trailing comma in SQL and leads to a syntax error.
🚀 Application
advanced2:30remaining
Generate dynamic WHERE clause with dbt for loop
You want to generate a dynamic WHERE clause in dbt SQL using a list of filters:
Which dbt Jinja code snippet correctly generates:
filters = ['age > 30', "country = 'US'", 'active = true'].Which dbt Jinja code snippet correctly generates:
WHERE age > 30 AND country = 'US' AND active = trueAttempts:
2 left
💡 Hint
Look for correct use of AND and no trailing AND.
✗ Incorrect
Option B correctly loops over filters, adding AND only between items, producing the exact desired WHERE clause.
🧠 Conceptual
expert1:30remaining
Why use for loops for dynamic SQL in dbt?
Which of the following is the best reason to use for loops in dbt to generate dynamic SQL code?
Attempts:
2 left
💡 Hint
Think about the purpose of templating and loops in code generation.
✗ Incorrect
For loops in dbt help automate repetitive SQL code generation, making code easier to maintain and less error-prone.