Macros
Learn how to reuse logic with dbt macros.
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:
Press + to interact
SELECTorder_date,SUM(potatoes) AS potatoesFROM {{ ref("vegetables") }}GROUP BY order_date
And we might have a similar query for tomatoes:
Press + to interact
SELECTorder_date,SUM(tomatos) AS tomatosFROM {{ 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 ...