DBT DBT Macros & Jinja 2 — Questions and Answers
Question 1: Which dbt macro is used to generate a cross-database compatible date-trunc expression?
- dbt.date_trunc() (Correct answer)
- dbt_utils.date_trunc()
- dbt.trunc_date()
- dbt_utils.trunc()
Correct answer: dbt.date_trunc()
`dbt.date_trunc(datepart, date)` is a built-in cross-database macro that adapts the date_trunc SQL function for each supported adapter.
Question 2: What does the `var()` function do in a dbt model?
- Declares a Jinja variable
- Reads a project variable defined in dbt_project.yml or passed via --vars (Correct answer)
- Retrieves an environment variable
- Creates a SQL variable
Correct answer: Reads a project variable defined in dbt_project.yml or passed via --vars
`{{ var('name', default) }}` reads variables from the `vars:` section of dbt_project.yml or those overridden at runtime with `--vars`.
Question 3: How do you pass a runtime variable override when running dbt?
- dbt run --set key=value
- dbt run --vars '{key: value}' (Correct answer)
- dbt run --env key=value
- dbt run --config key=value
Correct answer: dbt run --vars '{key: value}'
The `--vars` flag accepts a YAML dictionary string that overrides project variables for the duration of the run.
Question 4: What Jinja construct lets you loop over a list and generate repeated SQL fragments in dbt?
- {% repeat %}
- {% for item in list %} ... {% endfor %} (Correct answer)
- {% each item %} ... {% end %}
- {% loop %} ... {% endloop %}
Correct answer: {% for item in list %} ... {% endfor %}
`{% for item in list %}...{% endfor %}` iterates over a list and renders the body for each element, enabling dynamic SQL generation.
Question 5: What is the purpose of `adapter.dispatch()` in dbt macros?
- Sends the compiled SQL to the warehouse
- Finds the correct macro implementation for the active database adapter (Correct answer)
- Dispatches a dbt Cloud run via API
- Routes traffic to different dbt targets
Correct answer: Finds the correct macro implementation for the active database adapter
`adapter.dispatch()` enables polymorphism by resolving a macro to its adapter-specific implementation (e.g., Snowflake vs BigQuery).
Question 6: Which built-in dbt macro returns a surrogate key hashed from one or more column expressions?
- dbt.hash_columns()
- dbt_utils.generate_surrogate_key() (Correct answer)
- dbt.surrogate_key()
- dbt_utils.hash_key()
Correct answer: dbt_utils.generate_surrogate_key()
`dbt_utils.generate_surrogate_key([col1, col2])` concatenates and hashes the specified columns to produce a consistent surrogate key.
Which dbt macro is used to generate a cross-database compatible date-trunc expression?