About Skills Projects Blog Contact View my CV ↗ Español
dbt hands-on: modern transformations from theory to warehouse

dbt hands-on: modern transformations from theory to warehouse

Hands-on dbt guide: models, sources, tests, macros, seeds, snapshots, docs, lineage, incremental models, and performance on DuckDB, Postgres, and Snowflake.

By Omar Flores
Table of Contents

It is 7:40 on a Monday. The revenue dashboard shows a 12% drop and your manager wants to know why. You open the analytics repository and find forty-three SQL files, three of them named revenue_final, one revenue_final_v2_OK, and another revenue_final_v2_OK_THIS_ONE. Nobody knows which one feeds the dashboard. Four hours later you learn that someone changed a JOIN on Friday and nobody noticed because there was not a single test.

dbt exists so that Monday does not repeat itself. It does not promise magic: it forces you to give a name, a contract, and a map to the transformations you already write in SQL.

The problem dbt solves

Every warehouse ends up with an invisible DAG: a hundred queries that depend on each other, executed in an order only the person who wrote them understands. When that person goes on vacation, the order becomes folklore.

dbt makes three things explicit that used to live in someone’s head:

  • Dependencies: {{ ref('stg_orders') }} is not a path, it is an edge in the graph. dbt computes the order and runs in parallel whatever can run in parallel.
  • Contracts: tests turn assumptions (“this id is unique”) into checks that fail the build.
  • Context: documentation, lineage, and metadata generated from the same code that transforms the data.

The result is not just cleaner SQL. A change in stg_orders propagates visibly, and a broken test stops downstream models instead of contaminating the dashboard.

What dbt is and what it is not

dbt is a transformation framework: you write models in SQL (or Python), it compiles them with Jinja, and runs them in your warehouse. It does not move data from an API and it does not replace an orchestrator. It is the T in ELT, with software-engineering steroids.

dbt does dbt does not
Model, test, and document transformations Extract data from APIs or operational databases
Compute execution order with ref() Schedule jobs by itself (dbt platform does; dbt Core does not)
Version SQL and config in Git Store data (your warehouse does that)
Generate lineage and docs Replace Airflow, Dagster, or Prefect

There are two flavors: dbt Core, open source and command-line driven, and dbt platform (formerly dbt Cloud), which adds an IDE, scheduler, and governance. The examples use dbt Core 1.12; with dbt v2/Fusion most of the model and config syntax carries over, though some commands and features change.

A minimal project

Install dbt and the DuckDB adapter in an isolated environment:

uv venv
source .venv/bin/activate
uv pip install dbt-core dbt-duckdb
dbt init shop
cd shop

Structure:

shop/
├── dbt_project.yml
├── models/
│   ├── staging/
│   │   ├── stg_orders.sql
│   │   └── _sources.yml
│   └── marts/
│       ├── fct_revenue.sql
│       └── _marts.yml
├── macros/
├── seeds/
├── snapshots/
└── tests/

dbt_project.yml declares the project name, profile, and folder-level materializations:

name: shop
version: "1.0.0"
config-version: 2
profile: shop

models:
  shop:
    staging:
      +materialized: view
    marts:
      +materialized: table

The profile lives outside the repo (~/.dbt/profiles.yml) because it holds credentials. For DuckDB, one path is enough:

shop:
  target: dev
  outputs:
    dev:
      type: duckdb
      path: "shop.duckdb"
      schema: main
      threads: 8

The first model, models/staging/stg_orders.sql:

select
    id as order_id,
    customer_id,
    channel,
    cast(created_at as date) as date,
    cast(created_at as timestamp) as created_at,
    status,
    total_cents / 100.0 as total
from {{ source('raw', 'orders') }}
where status is not null

Build:

dbt debug
dbt build

dbt build runs seeds, snapshots, models, and tests in DAG order. For models only, use dbt run; for tests only, dbt test.

Sources: the boundary between loading and transforming

A source is a table that already exists in the warehouse and that dbt does not create: the output of Fivetran, Airbyte, or a Parquet file in DuckDB. Declaring it lets you test it, document it, and measure its freshness.

version: 2

sources:
  - name: raw
    schema: raw
    config:
      freshness:
        warn_after: {count: 12, period: hour}
        error_after: {count: 24, period: hour}
      loaded_at_field: _loaded_at
    tables:
      - name: orders
      - name: payments
      - name: events

In dbt 1.9+, freshness and loaded_at_field live under config; earlier versions had them at the source root. The rule is simple: source() for what you do not control, ref() for what you build. Never hardcode raw.orders: it breaks lineage.

Freshness is measured with dbt source freshness (in dbt v2, dbt freshness --resource-type source). If the source is 30 hours behind, do not rebuild the marts.

Models and materializations

A model is a named select. dbt materializes it according to the strategy you choose:

Materialization What it does When to use it
view Creates a view on every run Staging and light transformations
table Rebuilds the full table Marts queried by BI
incremental Inserts or updates only new rows Events and large tables
ephemeral Not persisted; injected as a CTE Intermediate logic used by few models
materialized_view Delegates refresh to the engine When the warehouse supports it

The convention that ages best is staging → intermediate → marts: staging renames and casts, intermediate joins and calculates, marts expose facts and dimensions. Each layer uses ref() to declare the previous one:

select
    p.date,
    p.channel,
    count(distinct p.order_id) as orders,
    sum(g.amount) as revenue
from {{ ref('stg_orders') }} p
left join {{ ref('stg_payments') }} g using (order_id)
where p.status = 'paid'
group by 1, 2

ref() resolves the physical name for the environment and creates the dependency. That is why --select +fct_revenue runs everything it needs, and fct_revenue+ runs everything that depends on it.

Tests: the contract that runs

A dbt test is a query that returns rows when something is wrong. Generic tests cover 80% of cases:

version: 2

models:
  - name: stg_orders
    description: "One row per order, cleaned and typed."
    columns:
      - name: order_id
        data_tests:
          - unique
          - not_null
      - name: status
        data_tests:
          - accepted_values:
              values: ["pending", "paid", "shipped", "cancelled"]
      - name: customer_id
        data_tests:
          - relationships:
              to: ref('stg_customers')
              field: customer_id

For rules that do not fit a generic test, write a singular test in tests/:

-- tests/assert_positive_total.sql
select order_id, total
from {{ ref('stg_orders') }}
where total < 0

The test fails if it returns at least one row. That is the whole API.

In dbt build, if a test on stg_orders fails, downstream models are marked SKIP instead of being built with bad data. A test with severity: warn alerts but does not block; a test that never blocks is documentation in disguise. Unit tests (dbt 1.8+) test model logic with fixed inputs before touching the warehouse.

Macros and seeds

A macro is a reusable Jinja function for repeated rules and for adapting SQL across engines:

{% macro safe_divide(numerator, denominator) %}
    case
        when {{ denominator }} = 0 then null
        else {{ numerator }} / {{ denominator }}
    end
{% endmacro %}
select
    date,
    {{ safe_divide('revenue', 'orders') }} as average_order_value
from {{ ref('fct_revenue') }}

For community-tested utilities, install dbt_utils in packages.yml and run dbt deps. Do not rewrite generate_surrogate_key by hand.

Seeds are versioned CSV files in seeds/ that dbt loads as tables. They are for small reference data (countries, currencies), not for ingestion. If a code has leading zeros, declare column_types in dbt_project.yml so they survive.

dbt seed

Snapshots: the history an UPDATE erases

Operational tables overwrite the past. An order moves from pending to paid and the previous state disappears. A snapshot implements type-2 SCD: it stores each version with dbt_valid_from and dbt_valid_to.

snapshots:
  - name: orders_snapshot
    relation: source('raw', 'orders')
    config:
      schema: snapshots
      unique_key: id
      strategy: timestamp
      updated_at: updated_at
      hard_deletes: new_record

Run it with dbt snapshot; schedule it hourly or daily. Two details matter: the unique_key must truly be unique, and the snapshot only sees the state at run time; if an order changes three times between runs, it captures none of the intermediate transitions. For high-frequency changes, use CDC.

Docs and lineage

Documentation lives next to the code. You can describe models and columns in YAML, and reuse long blocks with {% docs %}:

{% docs fct_revenue %}
One row per day and channel. Excludes cancelled orders and rejected payments.
{% enddocs %}

Then reference it with description: "{{ doc('fct_revenue') }}" in the model YAML, and run dbt docs generate followed by dbt docs serve.

The site is built from manifest.json and catalog.json, so lineage reflects the last build, not a diagram from six months ago. dbt ls --select +fct_revenue tells you what will run before it runs, and exposures declare which dashboard consumes each mart. When someone asks what breaks if you change a column, the answer is in the graph.

Incremental models

An incremental model transforms everything the first time and only new rows afterward. Use it when the table grows through events and the full build is too slow:

{{
    config(
        materialized='incremental',
        unique_key='event_id',
        on_schema_change='append_new_columns'
    )
}}

select
    event_id,
    user_id,
    type,
    occurred_at,
    properties
from {{ source('raw', 'events') }}

{% if is_incremental() %}
  where occurred_at >= (
      select coalesce(max(occurred_at), '1900-01-01') from {{ this }}
  )
{% endif %}

is_incremental() is true only if the table already exists, you are not running --full-refresh, and the model is configured as incremental. The filter must also be valid when it returns everything: hence the coalesce with an ancient date.

Strategies: append (insert only), delete+insert (delete matching keys and reinsert), merge (native upsert), and microbatch (time windows). Availability depends on the adapter; merge on DuckDB requires a recent engine version. If the unique_key is not unique, merge duplicates or fails: validate it with a unique test.

Add a one- or two-day lookback window for late-arriving data, and use --full-refresh when historical logic changes. An incremental model with new logic applied only to new rows produces an inconsistent table.

dbt with DuckDB, Postgres, and Snowflake

The same project can target different engines by switching targets. You develop on DuckDB, validate on Postgres, and publish to Snowflake.

DuckDB is great for local development, CI, and Parquet analysis. To read S3, declare extensions: [httpfs] and an S3 secret in the profile.

Postgres works well as a staging environment or for small teams:

    dev:
      type: postgres
      host: localhost
      port: 5432
      user: "{{ env_var('PG_USER') }}"
      password: "{{ env_var('PG_PASSWORD') }}"
      dbname: shop
      schema: analytics
      threads: 8

Snowflake is the usual production target. Use a dedicated role and a warehouse you can suspend:

    prod:
      type: snowflake
      account: "{{ env_var('SNOWFLAKE_ACCOUNT') }}"
      user: "{{ env_var('SNOWFLAKE_USER') }}"
      password: "{{ env_var('SNOWFLAKE_PASSWORD') }}"
      role: TRANSFORMER
      database: ANALYTICS
      warehouse: TRANSFORM_WH
      schema: MARTS
      threads: 16

In production, prefer key-pair auth or SSO over a password in an environment variable. And do not give the transformation role write access to raw: if dbt can modify sources, lineage stops being a guarantee.

Performance, common errors, and when NOT to use dbt

Performance. Run only what you need (--select +fct_revenue), raise threads carefully, materialize as tables only what is queried heavily, and use state:modified+ to rebuild only what changed against the production manifest:

dbt build --select state:modified+ --state ./prod-manifest
dbt retry

--defer reuses relations from another environment without rebuilding them; dbt clone creates lightweight copies when the adapter supports it. Before optimizing, check time per node in manifest.json: there is usually a model scanning a huge table without a filter.

Common errors.

Symptom Likely cause Fix
relation does not exist Wrong source or target Check dbt debug, schema, permissions
Duplicates in incremental Non-unique unique_key Add a unique test and a surrogate key
depends on a node named ... not found Misspelled ref() or disabled model dbt ls and fix the name
Slow build view on view or missing filters Materialize intermediates and inspect the plan

When NOT to use dbt. If you need second-level latency, transactional writes, or ingestion, dbt is not the tool. It is also not for a one-off script nobody will run again, or for teams without a warehouse. dbt shines when there is SQL to maintain, several people touching it, and data that keeps growing.

Checklist.

  • Does every model have a business name and description?
  • Are sources declared and tested?
  • Are incremental unique_key columns truly unique?
  • Do critical tests block the build instead of only warning?
  • Does the project run in CI against an ephemeral environment?
  • Do secrets live outside the repo?

dbt does not turn anyone into an analytics engineer by installing a package. It forces you to give a name, a contract, and a map to what used to be a loose script. And when the dashboard drops again on a Monday, the question will no longer be which script feeds it, but which test failed.