dbt Jinja integrates the Jinja templating engine with dbt to generate dynamic, reusable SQL, macros, and configurations at compile time.
dbt Jinja is the fusion of the Jinja templating language with dbt, letting data engineers inject variables, control flow, and macros into SQL so that dbt compiles parameterized queries into runnable SQL statements.
During a dbt run
, dbt reads a model file, evaluates Jinja expressions inside double curly braces {{ }}
or blocks {% %}
, and writes plain SQL to the target/compiled directory before executing against your data warehouse.
Jinja eliminates repetitive code by abstracting environment-specific schema names, dates, and column lists into variables, reducing copy-paste errors and enabling single-source-of-truth logic across hundreds of models.
Key features include built-in macros like ref()
and source()
, custom macro creation in macros/
folders, filters such as | upper
, and control structures like {% if target.name == 'prod' %}
.
Create a model file, import variables, and wrap dynamic pieces in Jinja syntax. dbt will compile the template into concrete SQL, respecting your warehouse dialect.
{{ config(materialized='table') }}
select *
from {{ target.database }}.{{ var('schema_prefix', 'analytics') }}_events.raw_clicks
This model swaps the schema prefix via var()
, letting dev and prod share logic while writing to separate locations.
Keep Jinja minimal in models; extract complex logic into macros for readability. Add tests for macro outputs and document variables in dbt_project.yml
so teammates understand required inputs.
Overusing Jinja inside SELECT clauses can hide logic; prefer CTEs or macros. Avoid hard-coding env names—use target
. Never mutate global state inside macros; return values instead.
Galaxy’s context-aware SQL editor renders Jinja syntax highlighting, autocompletes macro names, and lets you compile models locally to preview the final SQL, speeding up dbt development.
Jinja templating turns static SQL into reusable, parameter-driven code, letting teams rapidly adapt data models to new schemas, business logic, or warehouse targets without rewriting queries. This accelerates analytics development cycles, enforces consistency across projects, and reduces maintenance overhead—critical for modern data engineering workloads where change is constant.
Add vars:
in dbt_project.yml
or pass with --vars '{key: value}'
when running dbt.
Only functions registered as macros or filters are allowed. Pure Python is blocked for security and portability.
Galaxy autocompletes macros, highlights Jinja blocks, and lets you preview compiled SQL, eliminating round-trips to the CLI.
Yes, Jinja works in tests, snapshots, and seeds the same way it does in models—dbt compiles them before execution.