Jinja in dbt
dbt models are SQL with Jinja mixed in: placeholders, loops and conditions that are filled in before the SQL reaches the warehouse. This lesson shows the three kinds of Jinja tags and how to see the SQL they produce.
Pipelines in production · dbt · Silver · Jinja and reuse, lesson 1 of 4
On this page
Read first: What dbt is (and is not) (skip if you know it)
In plain words first
A mail merge letter has blanks and rules: "Dear {name}", "if the customer is premium, add this paragraph". The printer fills them in before printing.
Jinja is the mail merge for SQL: dbt fills in the blanks and runs the rules first, then sends plain SQL to the warehousewarehouse: A database built for analytics on large tables, like Snowflake, BigQuery, Databricks or Redshift. dbt runs its SQL there. Learn more →.
Three kinds of tags
dbt renders every modelmodel: A SELECT statement in a .sql file. dbt runs it and saves the result in the warehouse as a table or view named after the file. Learn more → with Jinja before sending it to the warehouse. Jinja knows nothing about SQL: it produces text, and the text happens to be SQL.
| Tag | Means | Example |
|---|---|---|
{{ ... }} | An expression: print its value into the SQL | {{ ref('stg_invoices') }}, {{ var('start_date') }} |
{% ... %} | A statement: logic that prints nothing itself | {% if %}, {% for %}, {% set %} |
{# ... #} | A comment, removed from the compiled SQL | {# TODO: drop after migration #} |
A SQL comment -- {{ ref('x') }} is still rendered by Jinja, and still creates a dependency. Comment Jinja out with {# #}.
Loops: SQL that writes SQL
Listening time per device type, one column per device, needs one nearly identical line per device. Write the list once and let a loop write the lines:
{% set devices = ['phone', 'desktop', 'smart_speaker'] %} select account_id, {% for d in devices %} sum(case when device_type = '{{ d }}' then seconds_played else 0 end) as {{ d }}_seconds {%- if not loop.last %},{% endif %} {% endfor %} from {{ ref('stg_plays') }} group by account_id
Compiles to
select account_id, sum(case when device_type = 'phone' then seconds_played else 0 end) as phone_seconds, sum(case when device_type = 'desktop' then seconds_played else 0 end) as desktop_seconds, sum(case when device_type = 'smart_speaker' then seconds_played else 0 end) as smart_speaker_seconds from analytics.dbt_alice.stg_plays group by account_id
loop.lastis true on the final iteration, so the last column gets no trailing comma. (loop.firstandloop.indexexist too.)- A
-inside a tag, as in{%-, removes the whitespace and newline on that side, which keeps compiled SQL tidy. It changes layout only, not meaning. else 0matters: without it an account that never used a smart speaker gets null, not 0.
Variables and filters
{% set cutoff = '2024-01-01' %} {% set cols = ['plan_code', 'seats', 'country'] %} select account_id, {{ cols | join(', ') }} -- plan_code, seats, country from {{ ref('stg_accounts') }} where signed_up_on >= '{{ cutoff }}' and country in ({{ "'" ~ ['US', 'CA'] | join("', '") ~ "'" }})
Jinja variables live only while the file is rendered. To pass a value in from outside, use var() (next lesson).
Running a query from Jinja
Sometimes the list should come from the data, for example every device type that exists. run_query runs SQL during compilation. dbt parses the project before any model exists, so wrap it in {% if execute %}: during parsing execute is false and the query is skipped.
{% set q %} select distinct device_type from {{ ref('stg_plays') }} order by 1 {% endset %} {% if execute %} {% set devices = run_query(q).columns[0].values() %} {% else %} {% set devices = [] %} {% endif %}
dbt_utils.get_column_values wraps this pattern.Reading what you wrote
Run dbt compile --select model and open target/compiled/.../model.sql. In the dbt platform IDE, the Compile button shows the same. Most Jinja bugs (missing commas, a quote too many) are obvious in the compiled SQL and invisible in the template. {{ log('value: ' ~ x, info=true) }} prints to the console while compiling.
Common mistakes
- Commenting out a ref with -- — Jinja still renders it and dbt still adds the dependency. Use {# #}.
- Trailing comma after the last generated column — Use loop.last (or put the comma first) so the list closes cleanly.
- run_query without if execute — Fails at parse time, when the referenced table may not exist.
Key takeaways
- {{ }} prints, {% %} runs logic, {# #} comments; Jinja produces text that becomes SQL.
- Loops with loop.last generate repetitive columns without trailing commas.
- Whitespace control (-) only tidies the compiled SQL.
- Guard run_query with if execute, and read target/compiled to debug.
Interview prep
THE QUESTION
"Explain the difference between {{ }} and {% %} in dbt, and give a real use of a Jinja loop."
{{ }} prints an expression into the SQL, such as ref() or a variable; {% %} runs logic (if, for, set, macro) and prints nothing itself; {# #} is a comment removed before compiling. A typical loop turns a fixed list of values into one column each, for example listening seconds per device type, with loop.last to leave out the final comma. I check the result with dbt compile.Avoid: "Jinja is dbt's SQL dialect". Jinja is a text template engine; it generates SQL, which the warehouse then runs.
Follow-ups · answer out loud, then open
Follow-up"What does the execute variable mean?"
Scenario"A model that builds one column per value with a Jinja loop compiles to invalid SQL. How do you debug it?"
Trap"Commenting out a ref with -- removes the dependency."
Check yourself
3 questionsWhich tag removes text from the compiled SQL entirely?
Show the answer
{# #}. {# #} is a Jinja comment; -- is a SQL comment and Jinja inside it still renders.
In a for loop, how do you avoid a comma after the last generated column?
Show the answer
{% if not loop.last %},{% endif %}. loop.last is true on the final iteration.
Why wrap run_query in {% if execute %}?
Show the answer
Because during parsing execute is false and tables may not exist yet. Parsing renders Jinja without running queries.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Jinja and reuse · lesson 2 of 4 · 4 min readvar(), target and environments
Parameterise a model with vars, and make dev builds smaller and safer than prod with target.
Related lessons
Previous: Data tests
Primary sources: Jinja and macros · run_query