dbt Macros and Jinja: A Practical Guide with Compiled SQL
Jinja lets a dbt model use variables, loops, and conditions, and a macro makes a piece of that reusable. Each pattern here is shown with its source and the SQL dbt compiled from it.
On this page · 18 sections
- What Jinja does in a dbt model
- Set a variable and generate columns with a for loop
- Control the whitespace
- Write a reusable macro with arguments
- Use ref() inside a macro, with run_query and the execute guard
- Read settings with var() and target
- Call a macro from a package
- Common mistakes
- Nesting curly braces
- Forgetting that Jinja runs before the SQL
- Macros that hide logic
- When a macro is worth writing
- Frequently Asked Questions
- Where do dbt macros live, and how do you call one?
- How do you write an else if condition in dbt Jinja?
- How do you join or change strings in Jinja?
- Where should settings and credentials go in a dbt project?
- Primary sources and further reading
- Topic
- dbt for Analytics Engineers
- Category
- dbt
Jinja is the templating language that dbt renders in every model before any SQL reaches the database. A dbt macro is a named, reusable piece of Jinja that works like a function: it takes arguments and returns text, usually a fragment of SQL. Together they give a model variables, loops, and conditions, and dbt compiles the result to an ordinary query you can read. Each pattern below is shown with its source and the SQL that dbt compiled from it on PostgreSQL 16.
What Jinja does in a dbt model
A dbt model is a SQL select statement in a .sql file. dbt renders the Jinja in that file first and sends only the resulting SQL to the database. You recognize Jinja by its delimiters:
| Delimiter | Name | What it does |
|---|---|---|
{{ ... }} | Expression | Outputs a string into the SQL. Used to print a variable or call a macro, as in {{ ref('stg_payments') }} |
{% ... %} | Statement | Outputs nothing. Used for for loops and if conditions, to set variables, and to define macros |
{# ... #} | Comment | Is not executed and leaves nothing in the compiled SQL |
{{- ... -}}, {%- ... -%}, {#- ... -#} | Whitespace control | A minus sign next to a delimiter also strips the whitespace on that side |
To read the compiled SQL with dbt v1, the engine used here, run dbt compile and open the file under target/compiled/, or print one model with dbt compile --select order_payments. According to its upgrade guide, dbt v2 fails at parse time on a call to a macro or variable that does not exist, where dbt v1 reports it at compile time.
The examples use one seed, a CSV file that dbt loads as a table, named raw_payments:
payment_id,order_id,payment_method,amount_cents,paid_at
1,101,card,2500,2026-03-01
2,101,gift_card,500,2026-03-01
3,102,bank_transfer,12000,2026-03-02
4,103,card,1999,2026-03-02
5,103,card,801,2026-03-03
6,104,gift_card,1500,2026-03-04
Set a variable and generate columns with a for loop
{% set %} assigns a variable. {% for %} repeats the lines inside it once per item. This model, order_payments, writes one amount column per payment method:
{#- One row per order, one amount column per payment method. -#}
{%- set payment_methods = ['bank_transfer', 'card', 'gift_card'] -%}
select
order_id,
{%- for method in payment_methods %}
sum(case when payment_method = '{{ method }}' then amount else 0 end) as {{ method }}_amount,
{%- endfor %}
sum(amount) as total_amount
from {{ ref('stg_payments') }}
group by order_id
Compiled:
select
order_id,
sum(case when payment_method = 'bank_transfer' then amount else 0 end) as bank_transfer_amount,
sum(case when payment_method = 'card' then amount else 0 end) as card_amount,
sum(case when payment_method = 'gift_card' then amount else 0 end) as gift_card_amount,
sum(amount) as total_amount
from "ae_scratch_macros"."analytics"."stg_payments"
group by order_id
One line of SQL became three columns, and a new payment method is one more item in the list, which the documentation recommends setting at the top of the model. Inside a loop, Jinja provides variables such as loop.last: {{ ', ' if not loop.last }} printed a comma after every item except the last, which avoids a trailing comma when the loop writes the final column.
Control the whitespace
The minus signs in that model strip the whitespace next to a tag. A tag outputs nothing, but the line break after it stays. With every minus sign removed, the compiled file starts with three blank lines and has another before each column:
select
order_id,
sum(case when payment_method = 'bank_transfer' then amount else 0 end) as bank_transfer_amount,
The query is the same, and the documentation advises putting the readability of the model ahead of that of the compiled file.
Write a reusable macro with arguments
A macro is defined between {% macro %} and {% endmacro %} in a .sql file in the project's macros directory. A model becomes a view or a table. A macro creates nothing in the database: it returns text to the place it was called from. This one converts cents to dollars, and its second argument has a default:
{% macro cents_to_dollars(column_name, scale=2) -%}
round({{ column_name }} / 100.0, {{ scale }})
{%- endmacro %}
The staging model stg_payments calls it:
select
payment_id,
order_id,
payment_method,
{{ cents_to_dollars('amount_cents') }} as amount,
paid_at
from {{ ref('raw_payments') }}
Compiled:
select
payment_id,
order_id,
payment_method,
round(amount_cents / 100.0, 2) as amount,
paid_at
from "ae_scratch_macros"."analytics"."raw_payments"
The column name is in quotes because, inside Jinja, it is a string to paste into the SQL.
Use ref() inside a macro, with run_query and the execute guard
A macro can call ref(), and it can query the database and build SQL from the answer: run_query runs a statement and returns the result as a table object. This macro returns the payment methods found in the data:
{% macro get_payment_methods() %}
{% set query %}
select distinct payment_method
from {{ ref('stg_payments') }}
order by 1
{% endset %}
{% if execute %}
{{ return(run_query(query).columns[0].values()) }}
{% endif %}
{{ return([]) }}
{% endmacro %}
In the model, the hard-coded list becomes {%- set payment_methods = get_payment_methods() -%}, with no extra braces because the call is already inside a statement. It compiled to the same query as before. After a payment with a new method, wallet, was added to the seed, dbt build compiled a wallet_amount column with no edit to the model.
- The
executeguard. dbt first parses the project: it renders the Jinja to find everyrefand build the dependency graph, runs no SQL, and setsexecuteto false. Then it compiles and runs each model withexecutetrue. The guard keepsrun_queryout of the parse pass. Alog()call in the model printed the list once per pass:methods: [] methods: ('bank_transfer', 'card', 'gift_card') - The
refsits outside the guard. dbt saw it while parsing and recordedstg_paymentsas a dependency of any model that calls the macro. With the query moved inside{% if execute %}, a model that reachedstg_paymentsonly through the macro failed withdbt was unable to infer all dependencies for the model "payment_method_list".
The documentation warns that execute is also true during dbt compile and dbt docs generate, so a guarded query runs then too. Keep run_query for reads.
Read settings with var() and target
var() returns a project variable, defined under vars: in dbt_project.yml or passed for one run with --vars. target describes the active connection, with attributes such as target.name, target.schema, and target.type. With dbt v1 these come from the selected target in profiles.yml. This model keeps development builds small:
select
payment_id,
order_id,
amount,
paid_at
from {{ ref('stg_payments') }}
{% if target.name == 'dev' %}
where paid_at >= '{{ var("dev_start_date") }}'
{% endif %}
With dev_start_date: '2026-03-03' in the project file and the dev target, it compiled to:
select
payment_id,
order_id,
amount,
paid_at
from "ae_scratch_macros"."analytics"."stg_payments"
where paid_at >= '2026-03-03'
Running dbt compile --vars '{"dev_start_date": "2026-03-04"}' changed the date. Running dbt compile --target prod, against a second target whose schema is analytics_prod, removed the where line and changed what ref() resolved to:
from "ae_scratch_macros"."analytics_prod"."stg_payments"
A variable with no definition and no default (the second argument of var()) is a compilation error.
Call a macro from a package
A package is another dbt project whose macros and models are installed into yours. List it in packages.yml, run dbt deps, and prefix its macros with the package name:
packages:
- package: dbt-labs/dbt_utils
version: 1.4.1
{%- set payment_methods = dbt_utils.get_column_values(
table=ref('stg_payments'),
column='payment_method',
order_by='payment_method'
) -%}
With this in place of get_payment_methods(), order_payments compiled to the identical query. The package macro also takes a default argument, a list to use when the table has not been built yet. The hand-written macro has no such fallback: on an empty database, dbt compile ended with relation "analytics.stg_payments" does not exist, while the package macro with default=['card'] compiled a single card_amount column.
dbt's own cross-database macros, written so that one call works on different adapters, are called the same way under the dbt namespace: {{ dbt.dateadd('day', 7, 'paid_at') }} compiled to paid_at + ((interval '1 day') * (7)) on PostgreSQL.
Common mistakes
Nesting curly braces
Inside {{ }} or {% %} you are already in Jinja, so variables and function calls are written bare. A second pair of braces is passed along as literal text:
{% set amount_column = 'amount_cents' %}
select
{{ cents_to_dollars('{{ amount_column }}') }} as nested,
{{ cents_to_dollars(amount_column) }} as correct
from {{ ref('raw_payments') }}
select
round({{ amount_column }} / 100.0, 2) as nested,
round(amount_cents / 100.0, 2) as correct
from "ae_scratch_macros"."analytics"."raw_payments"
PostgreSQL rejected it with syntax error at or near "{". The opposite slip is a missing quote: {{ cents_to_dollars(amount_cents) }} makes Jinja look for a variable named amount_cents, find none, and print nothing, so it compiled to round( / 100.0, 2).
Forgetting that Jinja runs before the SQL
Jinja has finished before the database sees the query, so it cannot read a row. This looks as if it sets gift card payments to zero:
select
payment_id,
{% if payment_method == 'gift_card' %}0{% else %}amount{% endif %} as revenue
from {{ ref('stg_payments') }}
To Jinja, payment_method is an undefined variable, so the condition is false once, for the whole model:
select
payment_id,
amount as revenue
from "ae_scratch_macros"."analytics"."stg_payments"
It ran without an error and returned both gift card payments at full value. Logic that depends on row values belongs in a SQL case expression. For the same reason, run_query returns whatever the table held when the model was compiled.
Macros that hide logic
The documentation warns that Jinja can make models harder for other people to interpret, and recommends favoring readability even if some SQL is repeated. A macro that hides joins, filters, or a business rule forces every reader to open a second file. Describe each macro in a properties file under a macros: key, and put data tests on the models that call it. Here, dbt build ran four tests with the seed and three models and ended with PASS=8 WARN=0 ERROR=0.
When a macro is worth writing
This table is the site's advice.
| Situation | Use | Why |
|---|---|---|
| The same expression appears in several models and must stay identical | A macro with arguments | One definition to change, as with cents_to_dollars |
| Many near-identical columns in one model | A for loop in the model, no macro | The logic stays visible where it is used |
| The logic is used in one place | Plain SQL | Nothing is reused, so a macro only adds a file to open |
| A business rule with joins or filters that several models need | A model, selected with ref() | A model can be tested and appears in the dependency graph. See intermediate models |
The dbt hub lists the guides on the rest of a project.
Frequently Asked Questions
Where do dbt macros live, and how do you call one?
By default dbt looks for macros in .sql files in the macros directory, and one file can hold several. The macro-paths setting in dbt_project.yml changes the location. Call a macro with {{ macro_name() }}, or {{ package_name.macro_name() }} for one from a package.
How do you write an else if condition in dbt Jinja?
Use {% elif %} between {% if %} and {% else %}, and close with {% endif %}. With the dev target, {% if target.name == 'prod' %}full{% elif target.name == 'dev' %}sample{% else %}other{% endif %} compiled to sample.
How do you join or change strings in Jinja?
The ~ operator converts its operands to strings and joins them. Filters, applied with a pipe, change a value. {{ ('amount_' ~ 'usd') | upper }} compiled to AMOUNT_USD, {{ 'Gift Card' | lower | replace(' ', '_') }} to gift_card, and {{ 'card' | length }} to 4.
Where should settings and credentials go in a dbt project?
Put shared values in vars: and read them with var(). Use target for differences between environments. Keep credentials out of the project: the profile used here read the database password with env_var(). The documentation reserves the DBT_ENV_SECRET prefix for secrets, which dbt scrubs from its logs.
Primary sources and further reading
- Jinja and macros, dbt documentation. Delimiters, macros, quoting, and readability.
- Use Jinja to improve your SQL code, dbt documentation. Where to set variables.
- Template Designer Documentation, Jinja. Whitespace control,
loop.last,elif, undefined variables,~, and filters. - About ref function, dbt documentation. A
refhidden from parsing. - About run_query macro and About execute variable, dbt documentation. The two passes.
- About var function and About target variables, dbt documentation. Defaults and attributes.
- Packages, dbt documentation, and the dbt-utils README for
get_column_values. - Cross-database macros, dbt documentation. The
dbtnamespace. - Don't nest your curlies, dbt documentation.
- macro-paths, SQL models, env_var, and dbt compile, dbt documentation.
- Upgrading to v2, dbt documentation. Parse-time errors in dbt v2.
Every model and macro here was compiled and run with dbt Core 1.12.7 (dbt v1) and dbt-postgres 1.11.0 on PostgreSQL 16, with dbt_utils 1.4.1. The compiled SQL and messages are what dbt produced, with timestamps removed.
- dbt
dbt Seeds: What They Are, When to Use Them, and dbt seed Examples
Learn how to use dbt seeds to turn small CSV files into reliable, version-controlled tables in your warehouse. Clear use cases, configs, and examples.
- dbt
dbt Date Spine: dbt_utils.date_spine Example and Calendar Table
Build a reliable dbt date spine and calendar hub table fast. Use dbt_utils, variables for start/end dates, and proven patterns that scale.
- dbt
dbt Exposures: Define Downstream Dashboards and Track Lineage
dbt exposures connect dashboards, notebooks, and apps to the dbt DAG. Learn how to define, automate, and use them for safe changes and clear lineage.
