Search⌘ K
AI Features

Macros

Explore how to create and use Jinja macros in dbt to build reusable, parameterized SQL code. This lesson helps you understand defining macros, passing arguments, and returning values to streamline your data transformation workflows.

Introduction to macros

Jinja macros are reusable pieces of templated code. They’re similar to functions in other languages, such as Python.

Why do we need macros?

Sometimes, we find ourselves rewriting the same logic over and over again. For example, we might be grouping by day and summing potatoes sold:

MySQL
SELECT
order_date,
SUM(potatoes) AS potatoes
FROM {{ ref("vegetables") }}
GROUP BY order_date

And we might have a similar query for tomatoes:

MySQL
SELECT
order_date,
SUM(tomatos) AS tomatos
FROM {{ ref("vegetables") }}
GROUP BY order_date

Since the logic is the same, we can create a macro for that logic.

How to create a macro

Macros should be placed in a file in the macros folder. They start with a {% macro ...%} tag and end with a ...