Introduction
Macros help you write SQL code once and use it many times. This saves time and keeps your work neat.
Macros help you write SQL code once and use it many times. This saves time and keeps your work neat.
{% macro macro_name(arg1, arg2) %}
-- SQL code using {{ arg1 }} and {{ arg2 }}
{% endmacro %}
-- Use macro in SQL:
{{ macro_name(value1, value2) }}Macros are written inside {% %} tags.
You call macros using double curly braces {{ }}.
{% macro add_numbers(a, b) %}
{{ a }} + {{ b }}
{% endmacro %}
SELECT {{ add_numbers(5, 3) }} AS sum;{% macro filter_active(table) %}
SELECT * FROM {{ table }} WHERE status = 'active'
{% endmacro %}
{{ filter_active('users') }}This example defines a macro to calculate discounted prices. It then uses this macro in a query to get discounted prices for sales data.
{% macro calculate_discount(price, discount_rate) %}
ROUND({{ price }} * (1 - {{ discount_rate }}), 2)
{% endmacro %}
WITH sales AS (
SELECT 100 AS price, 0.1 AS discount_rate
UNION ALL
SELECT 200, 0.15
)
SELECT
price,
discount_rate,
{{ calculate_discount(price, discount_rate) }} AS discounted_price
FROM sales;Macros can take multiple arguments to make them flexible.
Use macros to avoid repeating complex SQL code.
Macros help keep your project DRY (Don't Repeat Yourself).
Macros let you reuse SQL code easily.
They make your SQL cleaner and easier to maintain.
Use macros to save time and reduce errors.
macros in dbt?{% macro select_active_users() %}
SELECT * FROM users WHERE active = true
{% endmacro %}SELECT id, name FROM ({{ select_active_users() }}){% macro get_orders() %}
SELECT * FROM orders
Pass the test and this pattern moves unknown