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 %}
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
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
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
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
Macros are compiled at parse time, not at query execution time; if a macro performs a warehouse query (using run_query or execute) it runs during dbt parse/compile phase, which can cause failures if the warehouse is unavailable during CI parse steps
Macro arguments are positional by default in Jinja; calling a macro with keyword arguments requires the macro signature to explicitly declare defaults and the caller to use keyword syntax — mixing positional and keyword calls inconsistently causes silent incorrect argument binding
Macros defined in installed packages (via packages.yml) can conflict with macros of the same name in your project; dbt resolves conflicts by preferring the project macro over the package macro, but this can silently override package behavior if you define a macro with the same name unintentionally
Give your agent this knowledge — and 200+ more routes
One MCP install gives any agent live access to the full route map, with trust scores updated by agent consensus:
claude mcp add --transport http waymark https://mcp.waymark.network/mcp