Skip to content
Silver 4 min read · Packages 2 practice problems ↓

Packages and dbt_utils

Many problems are already solved in dbt packages: date spines, surrogate keys, extra tests. This lesson shows how to install packages, pin their versions, and use the most common ones.

Pipelines in production · dbt · Silver · Jinja and reuse, lesson 4 of 4

Read first: Macros and custom generic tests (skip if you know it)

In plain words first

Instead of writing every recipe yourself, you can buy a trusted cookbook and use its recipes in your kitchen. You still choose which edition, so a reprint does not change your dishes overnight.

A package is that cookbook; packages.yml lists which ones, and which version.

Installing packages

YAML · packages.yml
packages:
  - package: dbt-labs/dbt_utils
    version: [">=1.3.0", "<2.0.0"]
  - package: dbt-labs/codegen
    version: 0.13.1
  - git: "https://github.com/acme/dbt-shared-macros.git"
    revision: v2.4.0           # a tag or commit, never a moving branch
Shell
dbt deps     # downloads into dbt_packages/ and writes package-lock.yml

Packages are just dbt projects: their macrosmacro: A reusable piece of Jinja, like a function that returns SQL. You call it with {{ my_macro(...) }}. Learn more →, tests and sometimes 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 → become available in yours, called with the package name as prefix, like {{ dbt_utils.star(...) }}. Commit package-lock.yml so every machine and CI run installs exactly the same versions; add dbt_packages/ to .gitignore.

Surrogate keys

Many tables have no single key column: a daily listening row is identified by account_id, track_id and listen_date together. A surrogate key hashes those columns into one value you can test for uniqueness and join on.

dbt · models/marts/fct_daily_listens.sql
select
    {{ dbt_utils.generate_surrogate_key(['account_id', 'track_id', 'listen_date']) }}
        as daily_listen_key,
    account_id,
    track_id,
    listen_date,
    plays
from {{ ref('int_plays_by_day') }}
dbt · Roughly what it compiles to
md5(cast(
    coalesce(cast(account_id as varchar), '_dbt_utils_surrogate_key_null_')
    || '-' ||
    coalesce(cast(track_id as varchar), '_dbt_utils_surrogate_key_null_')
    || '-' ||
    coalesce(cast(listen_date as varchar), '_dbt_utils_surrogate_key_null_')
as varchar)) as daily_listen_key
  • Each value is cast to text and nulls are replaced with a fixed marker, so a null in one column does not make the whole key null.
  • The - separator keeps (1, 23) and (12, 3) apart: without it both would hash "123".
  • The key is deterministic: the same inputs give the same key on every run, so it is safe to join on across models and runs.
Note: Older code uses dbt_utils.surrogate_key, which treated nulls differently and was removed in dbt_utils 1.0. Switching changes key values for rows with nulls, so it needs a full refresh of incremental modelsincremental model: A model that, after its first build, only processes new or changed rows and merges them into the existing table. Learn more → that store the key.

dbt_utils macros worth knowing

Macro or testDoes
star(from=ref('x'), except=['_loaded_at'])Lists every column of a relation except some, so you avoid select * drift.
date_spine('day', start, end)One row per day (or other period): the base for gap-free daily reports.
union_relations([ref('a'), ref('b')])Unions tables with different columns, filling missing ones with null.
get_column_values(ref('x'), 'device_type')Distinct values of a column, at compile time.
deduplicate(relation, partition_by, order_by)Keeps one row per key, portable across warehouseswarehouse: A database built for analytics on large tables, like Snowflake, BigQuery, Databricks or Redshift. dbt runs its SQL there. Learn more →.
Tests: unique_combination_of_columns, expression_is_true, accepted_range, recencyCommon rules as generic tests.

What packages cost

  • A package's macros run with your warehouse credentials. Use packages you trust, and pin versions.
  • Major upgrades change behaviour, as surrogate_key did. Read the changelog and run the full test suite.
  • Packages with models (for example sourcesource: A raw table loaded by another tool, declared in YAML so models can select from it with source() and dbt can test it and check its freshness. Learn more →-specific packages for Stripe or HubSpot) add models to your DAGDAG: The graph of models that ref() calls create. dbt uses it to build models in dependency order. Learn more →; disable the ones you do not need with +enabled: false.

Common mistakes

  • Pinning a git package to a branch — The code changes under you between runs. Pin a tag or commit.
  • Concatenating key columns without a separator — Different keys can produce the same string, and the same hash.
  • Not committing package-lock.yml — Different machines install different versions.

Key takeaways

  • Declare packages in packages.yml, install with dbt deps, and commit package-lock.yml.
  • generate_surrogate_key hashes several columns into one deterministic key, safe with nulls.
  • dbt_utils has macros (star, date_spine, union_relations) and tests worth knowing.
  • Packages run with your credentials and change between versions: pin and review them.

Interview prep

THE QUESTION

"You need a primary key for a table identified by three columns. What do you do in dbt?"

Generate a surrogate key with dbt_utils.generate_surrogate_key(['a', 'b', 'c']): it casts each column to text, replaces nulls with a marker, joins them with a separator and hashes the result, so the key is deterministic and nulls do not make it null. Then test it with unique and not_null, or test the combination directly with dbt_utils.unique_combination_of_columns.

Avoid: "we just install dbt_utils at the latest version". Pin versions, commit the lock file, and read changelogs.

Follow-ups · answer out loud, then open

Follow-up"Why use a hash surrogate key instead of an auto-increment id?"
A hash of the natural key is deterministic: rebuilding the table, or computing the key in another model, gives the same value, so joins and incremental merges stay consistent. Sequences change on every rebuild and need state.
Scenario"After upgrading dbt_utils, surrogate keys changed for some rows. Why?"
The old surrogate_key macro was replaced by generate_surrogate_key, which handles nulls differently, so keys for rows with nulls changed. Incremental tables and anything joining on the stored key need a full refresh.
Trap"md5 of col_a || col_b is a good enough key."
Without casts, null handling and a separator, a null makes the whole key null and different value pairs can concatenate to the same string.

Check yourself

3 questions

What does dbt deps do?

Show the answer

Installs the packages listed in packages.yml. It downloads packages into dbt_packages/.

Why does generate_surrogate_key put a separator between values?

Show the answer

So different combinations, like (1, 23) and (12, 3), do not produce the same string. Without a separator, both concatenate to 123.

In generate_surrogate_key, what happens when one input column is null?

Show the answer

The null is replaced with a fixed marker before hashing. Nulls are coalesced to a marker, so the key still exists.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · new module: Change over time · 5 min read
Incremental models
is_incremental(), {{ this }} and unique_key: process only new rows, and the first-run and re-run cases.

Related lessons

Previous: Macros and custom generic tests

Primary sources: Packages · dbt_utils