Macros for reusable SQL logic
📖 Scenario: You work as a data analyst who often writes similar SQL queries to calculate sales metrics for different regions. To save time and avoid repeating code, you want to create reusable SQL logic using dbt macros.
🎯 Goal: Build a dbt macro that calculates total sales for a given region, then use this macro in a model to get total sales for the 'East' region.
📋 What You'll Learn
Create a macro named
total_sales_by_region that takes a parameter region_nameThe macro should return a SQL snippet that sums the
sales_amount from the sales table filtered by region_nameCreate a dbt model that uses the macro to calculate total sales for the region 'East'
Print the resulting SQL query output
💡 Why This Matters
🌍 Real World
In real companies, analysts often write similar SQL queries for different filters or metrics. Macros let you write the logic once and reuse it, saving time and reducing errors.
💼 Career
Knowing how to create and use macros in dbt is valuable for data analysts and engineers to build scalable, maintainable data transformation pipelines.
Progress0 / 4 steps