dbt Jinja and Macros
Write SQL once, run it everywhere
Jinja makes dbt SQL dynamic: conditionals, loops, and macros that generate SQL once instead of copy-pasting it everywhere. Macros are how a team stops writing the same date-range CASE in ten models.
What you will learn
- Use Jinja expressions inside model SQL
- Create macros and call them with arguments
- Keep templating readable and debuggable
What is this?
dbt compiles models through Jinja, a templating language. {{ ... }} interpolates values and {% ... %} controls logic — conditionals, loops, comments. Macros are reusable Jinja functions stored in macros/, letting a team express 'the last N days with seasonality adjustments' in one callable name.
Why do you need it?
- Templating kills copy-pasted SQL that drifts between models.
- One macro change updates every caller — consistency across the warehouse.
- Config and compilation make SQL expressive without a new programming system.
Mental model
A form letter with blanks
A Jinja macro
You write the template once, fill the blanks per recipient, and never retype the paragraph. Fix the paragraph and every letter improves.
How it works
- Wrap model SQL in Jinja blocks for filters, config, or generated columns.
- Define macros in macros/ as {% macro name(args) %} ... {% endmacro %}.
- Call macros inside models to insert compiled SQL.
- dbt compiles the full result to plain SQL before running.
Models are templates compiled by Jinja into executable SQL.
In production
- A date-range macro powers every cohort table with one definition.
- A macro emits the same clean currency conversion for every market model.
- Jinja loops generate monthly partition selects instead of hand-written unions.
Best practices
- Keep macros small and test them; a macro failure ripples everywhere.
- Document macro args so callers do not guess.
- Compile before you run to inspect the final SQL for templating mistakes.
Common mistakes
- Building a sprawling macro that hides a false assumption in all callers.
- Templating syntax errors that surface only mid-run and look like SQL bugs.
- Using macros where a plain SQL model plus a comment would be clearer.
Debugging tips
- Use dbt compile to view the generated SQL when a model misbehaves.
- If a macro returns nothing, check whitespace and endmacro placement — the compiled SQL will show the gap.
Interview checkpoint
Quick quiz
To conditionally include SQL, a model uses
Macros live by default in the