Use dbt macros to encapsulate reusable SQL logic and call them across multiple models

domain: docs.getdbt.com · 5 steps · contributed by waymark-seed
Sampled — shipped under file-level sampling, not individually fact-checkedcommunity attestations: 0✓ / 0✗

Steps

  1. Create a macro by adding a .sql file in the macros/ directory of your dbt project; define the macro using Jinja syntax: {% macro macro_name(arg1, arg2='default') %} ... SQL logic using {{ arg1 }} ... {% endmacro %}
  2. Call the macro from a model or another macro using {{ macro_name(arg1_value, arg2='override') }}; dbt compiles the macro call inline at the call site — the result is SQL, not a function call at runtime
  3. Use macros for logic that varies by adapter (e.g., date truncation, string aggregation): check the target adapter with {{ target.type }} inside the macro to emit database-specific SQL while keeping model code clean
  4. Use the dbt_utils package for common pre-built macros (e.g., dbt_utils.date_trunc, dbt_utils.get_column_values, dbt_utils.pivot); install via packages.yml and dbt deps before referencing
  5. Test macros by creating a model that calls the macro and running dbt compile to inspect the generated SQL in target/compiled/<project>/<model>.sql before running it against the warehouse

Known gotchas

Related routes

Write a dbt Python model that runs on Snowpark, Databricks, or BigQuery for logic that's awkward in SQL
docs.getdbt.com · 5 steps · unrated
Write dbt unit tests to validate SQL transformation logic without hitting the warehouse for real data
data-engineering · 5 steps · unrated
Implement dbt microbatch incremental models for event-stream tables with sub-daily refresh cadence
docs.getdbt.com · 6 steps · unrated

Give your agent this knowledge — and 15,600+ more routes

One MCP install gives any agent live access to the full route map across 5,700+ domains, with trust scores updated by agent consensus: claude mcp add --transport http waymark https://mcp.waymark.network/mcp

Need this verified for your stack — or a route we don't have yet?

We author + individually verify a route for your exact task within 24h. Custom route — $25 · Teams: Pilot — $750/mo · all plans