Macros and custom generic tests
When the same SQL snippet appears in ten models, a macro lets you write it once and call it everywhere. This lesson shows how to write macros, pass arguments, and keep them readable.
Pipelines in production · dbt · Silver · Jinja and reuse, lesson 3 of 4
On this page
Read first: Jinja in dbt · Data tests (skip if you know them)
In plain words first
A chef writes the house dressing recipe once and says "add house dressing" in every salad recipe, instead of copying the ingredients each time. Change the dressing once, and every salad follows.
A macro is the house dressing: a named piece of SQL with arguments, pasted in wherever you call it.
A macro is a function that returns SQL
A macro lives in macros/, takes arguments, and returns text. Call it with {{ }} and the returned text is pasted into the SQL.
{% macro safe_ratio(num, den, if_zero=0) %} coalesce(cast({{ num }} as double) / nullif({{ den }}, 0), {{ if_zero }}) {% endmacro %}
select track_id, {{ safe_ratio('skips', 'plays') }} as skip_rate, {{ safe_ratio('seconds_played', 'plays', 'null') }} as avg_seconds from {{ ref('int_track_play_counts') }}
Compiles to
select track_id, coalesce(cast(skips as double) / nullif(plays, 0), 0) as skip_rate, coalesce(cast(seconds_played as double) / nullif(plays, 0), null) as avg_seconds from analytics.dbt_alice.int_track_play_counts
- Columns are passed as strings,
'skips': the macro pastes the names into SQL. Passingskipswithout quotes would look for a JinjaJinja: The template language dbt runs before sending SQL: {{ }} inserts a value, {% %} runs logic such as loops and ifs. Learn more → variable and print nothing. if_zero=0is a default; callers override it by keyword or position. Here'null'is SQL text, so the second column stays null for tracks never played.- Cast before dividing: in many warehouseswarehouse: A database built for analytics on large tables, like Snowflake, BigQuery, Databricks or Redshift. dbt runs its SQL there. Learn more → an integer divided by an integer is integer division, so 3 / 4 is 0.
When to write one
A macro earns its place when the same non-trivial expression appears in many modelsmodel: A SELECT statement in a .sql file. dbt runs it and saves the result in the warehouse as a table or view named after the file. Learn more → and must change everywhere at once: unit conversions, a company's fiscal calendar, a standard way to hash keys, a cross-warehouse function. A macro used once, or one that hides a model's core logic, makes the model harder to read than the SQL it replaced.
Custom generic tests
A generic test is a macro-like block that returns failing rows. It always receives model (the relation being tested) and column_name (when attached to a column), plus any arguments you define.
{% test not_in_future(model, column_name) %} select {{ column_name }} as bad_value from {{ model }} where {{ column_name }} > current_timestamp {% endtest %}
models:
- name: fct_plays
columns:
- name: played_at
data_tests:
- not_in_future
- name: uploaded_at
data_tests:
- not_in_future:
config:
severity: warn
A null timestamp is not in the future: null > current_timestamp is unknown, so the row is not returned and the test passes on nulls, like the built-in tests. If nulls are a problem, add not_null, which keeps each test about one rule.
{% test within_range(model, column_name, min_value, max_value) %} select {{ column_name }} as bad_value from {{ model }} where {{ column_name }} < {{ min_value }} or {{ column_name }} > {{ max_value }} {% endtest %}
Use it as - within_range: {min_value: 0, max_value: 100} on a percentage column. The YAML arguments arrive as Jinja values and are printed into the SQL, so a string argument needs quotes inside the YAML value ("'2020-01-01'"). Tests that compare two models, such as an orphan check, take a relation as an argument (to: ref('dim_accounts')) and use an anti join (left join ... where parent.key is null) rather than not in, because not in with a null in the subquery returns no rows at all.
Macros across warehouses
Package authors use adapter.dispatch to pick a warehouse-specific version of a macro: {{ return(adapter.dispatch('dateadd')(...)) }} calls snowflake__dateadd on Snowflake and default__dateadd elsewhere. You rarely need it in a single-warehouse project, but it explains the default__ names you see in package code. dbt also ships cross-database macros such as {{ dbt.dateadd(...) }} and {{ dbt.datediff(...) }}.
Common mistakes
- Passing a column without quotes — safe_ratio(skips, plays) looks for Jinja variables called skips and plays and prints nothing.
- Macros for logic used once — The reader has to open another file to understand the model.
- not in for orphan checks — One null in the parent column makes not in return nothing, so the test always passes.
Key takeaways
- A macro returns SQL text; arguments are usually column names passed as strings.
- Defaults make macros flexible without breaking existing calls.
- A custom generic test is a test block that returns failing rows, with model and column_name filled in by dbt.
- Handle nulls on purpose, and prefer anti joins to not in.
Interview prep
THE QUESTION
"Write a macro and a custom generic test, and explain what they compile to."
{% macro safe_ratio(num, den, if_zero=0) %} coalesce(cast({{ num }} as double) / nullif({{ den }}, 0), {{ if_zero }}) {% endmacro %}, called as {{ safe_ratio('skips', 'plays') }}, pastes that expression into the SQL at compile time. A generic test: {% test not_in_future(model, column_name) %} select {{ column_name }} from {{ model }} where {{ column_name }} > current_timestamp {% endtest %}, attached to columns in YAML; dbt fills in model and column_name and fails if any rows come back.Avoid: "macros are stored procedures". They run at compile time and return SQL text; nothing is stored in the warehouse.
Follow-ups · answer out loud, then open
Follow-up"How does a custom generic test know which table and column to test?"
model (the relation of the model or source the test is attached to) and column_name (when attached to a column), plus the arguments given in YAML.Scenario"The same 15-line CASE statement mapping country codes to regions is in eight models. What do you do?"
Trap"An orphan check is best written with not in."
Check yourself
3 questionsWhat does {{ safe_ratio('skips', 'plays') }} put into the model?
Show the answer
The SQL expression the macro returns, with the column names filled in. Macros return text that becomes part of the SQL.
Which two arguments does dbt pass to a column-level generic test?
Show the answer
model and column_name. model is the relation, column_name the column it is attached to.
A not_in_future test runs on a column where some values are null. What happens to those rows?
Show the answer
They are not returned, so they pass. null > current_timestamp is unknown, so WHERE does not return them.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Jinja and reuse · lesson 4 of 4 · 4 min readPackages and dbt_utils
packages.yml, dbt deps, and the dbt_utils macros interviews expect you to know, starting with surrogate keys.
Related lessons
Previous: var(), target and environments
Primary sources: Jinja and macros · Writing custom generic tests