Back to Advanced dbt

Macros and Jinja

Reusable SQL via Jinja templating. The DRY principle for SQL. FIND_VIDEO: search 'dbt macros jinja tutorial' — recommended channel: dbt Labs. Aim for 10 min or under.

30 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.

Ready to continue?

Mark this lesson as complete when you're ready to proceed.

Key moments

  1. Defining DBT Macros — Explains how macros function as reusable SQL blocks analogous to standard programming functions.
  2. Macro Architectural Benefits — Covers code maintainability, central logic management, and cross-database compatibility advantages.
  3. Role of Jinja in DBT — Introduces the Jinja templating engine and how it enables dynamic control flow in SQL.
  4. Expressions vs Statements — Contrasts double curly brace output syntax against percent sign control statement delimiters.
  5. Variables and Comments — Demonstrates variable assignment, Jinja comment delimiters, and whitespace control.
  6. Jinja Control Flow — Shows how to write conditional blocks and iterate over lists with for loops.
  7. Understanding Jinja Filters — Explains string and variable transformation methods applied via the pipe operator.
PDF notes

Frequently asked questions

What is the difference between a dbt macro and a standard database stored procedure?

A macro compiles into plain SQL text on your machine before running on the database, whereas stored procedures execute procedural logic natively inside the database engine.

Why does my compiled SQL have large gaps of whitespace around Jinja blocks?

Jinja preserves template linebreaks by default; use whitespace trimming hyphens like `{%-` and `-%}` to remove unwanted whitespace in output SQL.

Can I use Jinja control flow to filter out table rows dynamically?

Jinja controls what SQL code gets sent to the warehouse, so you can write dynamic `WHERE` clauses, but row-level filtering happens during query execution.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.