How to Write Macros in dbt

Last updated July 25, 2026 · By the SaturnSQL team

Macros are reusable Jinja functions defined with {% macro %} in .sql files under macros/. Call them anywhere with {{ my_macro(args) }}; they render to SQL at compile time. Package macros are namespaced, like dbt_utils.date_spine.

-- macros/cents_to_dollars.sql
{% macro cents_to_dollars(column_name, precision=2) %}
  ROUND({{ column_name }} / 100.0, {{ precision }})
{% endmacro %}

Calling it in a model

SELECT
  order_id,
  {{ cents_to_dollars('amount_cents') }} AS amount_usd
FROM {{ ref('stg_orders') }}

Macros run during compilation, not in the warehouse, so they are string templating: use them to avoid repeating SQL patterns, generate column lists, or wrap adapter-specific syntax. Run dbt compile to inspect the output.

Run this in SaturnSQL

SaturnSQL is a browser-based SQL editor for teams: shared query library, schema-aware autocomplete, and scheduled exports to Google Sheets and Slack.

Try it free

Related dbt guides

© 2026 Panda Capital Oy Ab. All rights reserved.