Datacoves logo

Ultimate dbt Jinja Functions Cheat Sheet

ByMayra Peña 21 mins read
Ultimate dbt functions cheatsheet
Key Takeaways
  • Core Functions: ref(), source(), log(), env_var(), var(), and more enhance dynamic SQL generation and workflow efficiency.​
  • Built-in Macros: run_query(), debug(), and others assist in executing SQL queries within macros and debugging.​
  • Custom Filters: as_bool, as_number, as_native, and more aid in data type conversions.​
  • Contextual Variables: config, this, target, thread_id, and others provide context-specific information within dbt models.​
  • Context Methods: set() and more enable advanced logic and data manipulation within macros.

Jinja is the feature of dbt Core (now dbt v1) that allows us to create dynamic SQL code. In addition to the standard Jinja library, dbt Core includes additional functions and variables to make working with dbt even more powerful out of the box.

See our original post, The Ultimate dbt Jinja Cheat Sheet, to get started with Jinja fundamentals like syntax, variable assignment, looping and more. Then dive into the information below which covers Jinja additions added by dbt Core.

This cheatsheet references the extra functions, macros, filters, variables and context methods that are specific to dbt Core.

Enjoy!

dbt Core: Functions

These pre-defined dbt Jinja functions are essential to the dbt workflow by allowing you to reference models and sources, write documentation, print, write to the log and more.

Get our free ebook dbt Cloud vs dbt Core

Comparing dbt Core and dbt Cloud? Download our eBook for insights on feature, pricing and total cost. Find the best fit for your business!

Get the PDF
Get free ebook dbt cloud

dbt Core: Macros

These macros are provided in dbt Core to improve the dbt workflow.

dbt Core: Filters

These dbt Jinja filters are used to modify data types.

dbt Core: Project context variables

These dbt core “variables” such as config, target, source, and others contain values that provide contextual information about your dbt project and configuration settings. They are typically used for accessing and customizing the behavior of your dbt models based on project-specific and environment-specific information.

Project Context Variables
adapters
dbt uses the adapter to communicate with the database. Setup correctly using the Database specific adapter i.e Snowflake, RedShift. The adapter has methods that will be translated into SQL statements specific to your database.
builtins The builtins variable is a dictionary containing keys for dbt context methods ref, source, and config.
{% macro ref(modelname) %}
    {% set db_name = builtins.ref(modelname).database | lower %}}
    {% if db_name.startswith('staging') or 
        db_name.endswith('staging')  %}
        {{ return(builtins.ref(modelname).include(database=false)) }}
    {% else %}
        {{ return(builtins.ref(modelname)) }}
    {% endif %}
{% endmacro %}
config
The config variable allows you to get configuration set for dbt models and set constraints that assure certain configurations must exist for a given model:

config.get('<config_key>', default='value'): Fetches a configuration named <config_key> for example "materialization". - If no default is provided or the configuration item is not defined, it this will return None
{%- set unique_key = config.get('unique_key', default='id') -%}
config.require("<config_key>"): Strictly requires a key named <config_key> is defined in the configuration. - Throws error if not set.
{%- set unique_key = config.require('unique_key') -%}
config.get and config.require are commonly seen in the context of custom materializations, however, they can be used in other macros, if those macros are used within a model, seed, or snapshot context and they have the relevant configurations set.
dbt_version
The dbt_version variable is helpful for debugging by returning the installed dbt version. This is the dbt version running not what you define in your project. e.g. If you make a project with dbt 1.3 and run it on another machine with dbt 1.6, this will say 1.6
execute
The execute variable is set to True when dbt runs SQL against the database such as when executing dbt run. When running dbt commands such as dbt compile where dbt parses your project but no SQL is run against the database execute is set to False.

This variable is helpful when your Jinja is relying on a result from the database. Wrap the jinja in an if statement.
{% set payment_method_query %}
  SELECT DISTINCT
    payment_method
  FROM {{ ref('raw_payments') }}
  ORDER BY 1
{% endset %}

{% set payment_methods = run_query(payment_method_query) %}

{% if execute %}
  {# Extract the payment methods from the query results #}
  {% set payment_methods_list = payment_methods.columns[0].values() %}
{% else %}
  {% set payment_methods_list = [] %}
{% endif %}
flags This variable holds the value of the flags passed in the command line such as FULL_REFRESH, STORE_FAILURES, and WHICH(compile, run, build, run-operation, test, and show). It allows you to set logic based on run modes and run hooks based on current commands/type.
{% if flags.STORE_FAILURES %}
--your logic
{% else %}
--other logic
{% endif %}
graph
The graph variable is dictionary that hold the information about the nodes(Models, Sources, Tests, Snapshots) in your dbt project.
model
This is the graph object of the current model. This object allows you to access the contents of a model, model structure and JSON schema, config settings, and the path to the model.
modules This variable contains Python Modules for working with data including:datetime, pytz, re, and itertools.
modules.<desired_module>.<desired_function> 
{% set now = modules.datetime.datetime.now() %}
project_name
This variable returns the name for the root-level project that is being run.
target
This variable contains information about your dbt profile target, such as your warehouse connection information.

Use the dot notation to access more such as:
target.name or target.schema or target.database, ect

dbt Core: Run context variables

These special variables provide information about the current context in which your dbt code is running, such as the model, schema, or project name.

Run Context Variables
database_schemas
Only available in the context for on-run-end. This variable allows you to reference the databases and schemas. Useful if using multiple different databases
invocation_id This function outputs a UUID every time you run or compile your dbt project. It is useful for auditing. You may access it in the query-comment, info dictionary in events and logs, and in the metadata dictionary in dbt artifacts.
results
Only available in the context for on-run-end. This variable contains a list of Results Objects. Allows access to the information populated in run results JSON artifact.
run_started_at
This variable outputs a timestamp for the start time of a dbt run and defaults to UTC. It Is a python datetime object. Use standard strftime formatting.
select
    '{{ run_started_at.strftime("%Y-%m-%d") }}' as run_start_utc
schemas
Only available in the context for on-run-end. This variable allows you to reference a list of schemas for models built during a dbt run. Useful for granting privileges.
selected_resources
This variable allows you to access a list of selected nodes from the current dbt command.
The items in the list depend on the parameters of —select, —exclude,—selector.
this
{{ this }} is the database representation of the current model. Use the dot notation to access more properties such as: {{ this.database }} and {{ this.schema }}.
thread_id The thread_id is a unique identifier assigned to the Python threads that are actively executing tasks, such as running code nodes in dbt. It typically takes the form of names like "Thread-1," "Thread-2," and so on, distinguishing different threads.

dbt Core: Context methods

These methods allow you to retrieve information about models, columns, or other elements of your project.

Context Methods
set(value, default) Allows you to use the python method set(), which converts an iterable into a unique set of values. This is NOT the same as the jinja expression set which is used to assign a value to a variable. This will return none if the value entered is not an iterable. In the example below both the python set() method and the jinja set expression are used to remove a duplicate element in the list.
{% set my_list = ['a', 'b', 'b', 'c'] %}
{% set my_set = set(my_list) %}
{% do print(my_set) %}


{# evaluates to {'a','b', 'c'} #}
set_strict(value) Same as the set method above however it will raise a TypeError if the entered value is not a valid iterable.
{% set my_set = set_strict(my_list) %}
exceptions Is used to raise errors and warnings in a dbt run:

raise_compiler_error will raise an error, print out the message. Model will FAIL.
exceptions.raise_compiler_error("Custom Error message")
warn will raise a compiler warning and print out the set method. Model will still PASS.
exceptions.warn("Custom Warning message") 
fromjson(string, default) Is used to deserialize a JSON string into a python dict or list.
fromyaml(string, default) Is used to deserialize a YAML string into a python dict or list.
tojson(value, default) Serializes a Python dict or list to a JSON string.
toyaml(value, default ) Serializes a Python dict or list to a YAML string.
local_md5
This variable locally creates an MD5 hash of the given string.
{%- set hashed_value = local_md5("String to hash") -%}
select 
     '{{ hashed_value }}' as my_hashed_value
zip(*args, default) This method is allows you to combine any number of iterables.
{% set my_list_a = [1, 2] %}
{% set my_list_b = ['Data', 'Coves'] %}
{% set my_zip = zip(my_list_a, my_list_b) | list %}
{% do print(my_zip) %}  

{# Result [(1, 'Data'), (2, 'Coves')] #}
zip_strict(value) Same as the zip method but will raise a TypeError if one of the given values are not a valid iterable.
{% set my_list_a = 123 %}
{% set my_list_b = 'Datacoves' %}
{% set my_zip = zip_strict(my_list_a, my_list_b) | list %}
{# This will fail #}

Please contact us with any errors or suggestions.

FAQ

How do config.meta_get and config.meta_require differ from config.get and config.require?

+

Starting with dbt 1.10, custom keys must be nested below the meta dictionary. In order to retrieve these values, you must use config.meta_get(‘key’, default=‘value’) to fetch a meta dictionary config value and it can optionally return a default if it is not set. config.meta_require(‘key’) strictly requires the config meta key to exist and throws a compilation error if it is missing. Use config.meta_get() for optional meta settings and config.meta_require() when a meta value is mandatory.

What are dbt Jinja filters and when should I use as_bool, as_number, and as_native?

+

dbt Jinja filters coerce Jinja output into specific Python types. as_bool converts a value to a boolean, as_number converts it to a numeric type, and as_native returns the native Python type such as a list, dict or tuple. These matter most with env_var(), since environment variables always come back as strings. For example, {{ env_var('DB_PORT') | as_number }} ensures the port is treated as an integer rather than a string.

What does run_query() return and how do I use the result?

+

run_query() executes SQL and returns an Agate table object, not a Python list. To use the result you need to extract values from it, most commonly the first column with .columns[0].values(). Always wrap run_query() inside an {% if execute %} block to avoid errors during the parse phase, when no SQL has been run yet.

What does the execute variable do and why does it matter?

+

execute is set to True only when dbt is running SQL against the database (during dbt run or dbt test) rather than parsing the project. During the parse phase, execute is False and no SQL is executed. This matters when your Jinja logic depends on query results. If you try to call run_query() without wrapping it in {% if execute %}, dbt will throw a compilation error during parsing because no data has been returned yet.

What is the config variable and how does config.get() differ from config.require()?

+

The config variable provides access to the configuration set for a dbt model. config.get(‘key’, default=‘value’) safely fetches a config value and returns a default if it is not set. config.require(‘key’) strictly requires the config key to exist and throws a compilation error if it is missing. Use config.get() for optional settings and config.require() when a config value is mandatory for the model to run correctly.

What is the difference between ref() and source() in dbt?

+

Use ref() to reference another dbt model and source() to reference a raw table that something outside dbt loaded into your warehouse. Both resolve the correct schema and table name at compile time, and dbt uses them to build the lineage graph automatically. That distinction is how dbt tracks lineage from raw data through to your final models.

What is the difference between var() and env_var() in dbt?

+

var() pulls values defined in dbt_project.yml or passed on the CLI with --vars. It suits project-level configuration like date ranges or feature flags. env_var() reads environment variables from the operating system or your dbt platform, which suits secrets, credentials and environment-specific settings. Never use env_var() directly in model SQL for sensitive values, since those can appear in compiled SQL or logs. Use DBT_ENV_SECRET_ prefixed variables for secrets.

What is the modules variable in dbt Jinja and what can it do?

+

The modules variable gives you access to built-in Python standard library modules directly inside Jinja. The available modules include datetime, pytz, re, and itertools. This makes it possible to work with dates, run regex operations, and manipulate iterables inside your macros without writing a Python model. A common use case is getting the current date: {% set today = modules.datetime.date.today() %}.

What is the target variable and what information can I access from it?

+

target contains information about your active dbt profile connection. You can access target.name (the name of your target, such as dev or prod), target.schema, target.database, and target.type (the warehouse adapter). It is widely used in macros to write conditional logic that behaves differently across environments, for example only enabling certain tests or materializations in production.

What is the this variable and how is it used?

+

{{ this }} represents the database object of the model currently being compiled, and gives you this.database, this.schema and this.name. It is most often used in incremental models to filter new rows against the existing table, for example WHERE updated_at > (SELECT MAX(updated_at) FROM {{ this }}). It saves hardcoding schema or table names.

When should I use log() vs print() in dbt macros?

+

Both write messages to stdout, but log(msg, info=True) writes to both the log file and stdout, while log(msg, info=False) writes only to the log file. print() is equivalent to log() with info=True. Use log() with info=False for verbose debugging you only want in logs. Use print() or log(…, info=True) when you need the message visible during an active dbt run.

Last updated onApril 10, 2024
Mayra Peña
Mayra Peña
Author

Data Engineering | Technical Customer Success.

Solving enterprise data challenges quickly with dbt & Airflow.

Continue reading

End-to-end data analytics with Managed dbt and Airflow

Don’t let platform limitations or maintenance overhead hold you back.

Noel gomez

Subscribe to our newsletter & be a part of our Exclusive Crew!

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Datacoves Logo

Datacoves is an enterprise DataOps platform with Managed dbt and Airflow for data transformation and orchestration, as well as VS Code in the browser for development

LinkedIn X YouTube
Datacoves is snowflake ready technology badge
© 2026 Datacoves. All rights reserved.
Privacy Policy Terms of Service Sitemap

Apache, Apache Airflow, Airflow, Apache Superset, the Airflow logo, the Apache feather logo, Superset, and the Superset logo are trademarks of the Apache Software Foundation. Dbt, dbt core, dbt logo are trademarks of the dbt Labs, Inc. Airbyte, Airbyte logo are trademarks of the Airbyte, Inc. Snowflake, Snowflake logo are trademarks of the Snowflake Inc.