dbt
Intermediate 15 min read dbt

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.

dbtjinjamacrosconfigdynamic SQLtemplating
Before we start

What you will learn

  • Use Jinja expressions inside model SQL
  • Create macros and call them with arguments
  • Keep templating readable and debuggable
Introduction

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.

Motivation

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.
Think about it

Mental model

Imagine

A form letter with blanks

Think of

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.

Mechanics

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.

Template
Macros
Compile
Run
Real world

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.
Guidelines

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.
Watch out

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.
When things break

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.
Interviews

Interview checkpoint

Test yourself

Quick quiz

0/2
1

To conditionally include SQL, a model uses

2

Macros live by default in the

Go deeper

Official documentation