dbt · Macros, Packages & Advanced

Jinja in dbt

Easyjinjatemplatingcompile

Interview question

How does Jinja work in dbt, and why does dbt use it?

How to answer

The short answer

Jinja is a templating language. In dbt, your .sql files are templates that compile into plain SQL before the warehouse executes them.

What Jinja enables

  • ref() / source() resolution
  • config(), is_incremental(), {{ this }}
  • {% if %}, loops, macros
  • Environment-aware SQL without maintaining 5 copies of a query

Example

SQL
select *
from {{ ref('stg_orders') }}
{% if var('exclude_test_orders', true) %}
where is_test = false
{% endif %}

Compiled SQL has no Jinja left; the warehouse only sees SQL.

Mental model

Output
model.sql (SQL + Jinja)
        |
   dbt compile
        |
  target/compiled/.../*.sql  (pure SQL)
        |
   warehouse executes

Debugging tip

Use dbt compile --select model and read target/compiled when Jinja behavior is confusing.

Interview tip: "Jinja is compile-time. Heavy procedural logic belongs in macros carefully; the warehouse still does the data processing."