Skip to content

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:

DelimiterNameWhat it does
{{ ... }}ExpressionOutputs a string into the SQL. Used to print a variable or call a macro, as in {{ ref('stg_payments') }}
{% ... %}StatementOutputs nothing. Used for for loops and if conditions, to set variables, and to define macros
{# ... #}CommentIs not executed and leaves nothing in the compiled SQL
{{- ... -}}, {%- ... -%}, {#- ... -#}Whitespace controlA 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 execute guard. dbt first parses the project: it renders the Jinja to find every ref and build the dependency graph, runs no SQL, and sets execute to false. Then it compiles and runs each model with execute true. The guard keeps run_query out of the parse pass. A log() call in the model printed the list once per pass:
    methods: []
    methods: ('bank_transfer', 'card', 'gift_card')
  • The ref sits outside the guard. dbt saw it while parsing and recorded stg_payments as a dependency of any model that calls the macro. With the query moved inside {% if execute %}, a model that reached stg_payments only through the macro failed with dbt 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.

SituationUseWhy
The same expression appears in several models and must stay identicalA macro with argumentsOne definition to change, as with cents_to_dollars
Many near-identical columns in one modelA for loop in the model, no macroThe logic stays visible where it is used
The logic is used in one placePlain SQLNothing is reused, so a macro only adds a file to open
A business rule with joins or filters that several models needA 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

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.