dbt: Models, Tests, Macros, Materializations
Learn dbt for data transformations: models, tests, macros, materializations, seeds, snapshots, and production patterns for analytics engineers.
Introduction
dbt (data build tool) transforms data inside your warehouse using plain SQL. Raw data lands in the warehouse first (that’s the E-L part of ELT), then dbt handles the T: you write SELECT statements as models, dbt compiles them into tables and views, resolves dependencies, and runs everything in the right order.
It also brings software engineering discipline to analytics: version control, automated tests, environments, documentation, and reusable code — the things SQL scripts in a shared folder never had. The trade-off is real though: dbt only transforms. It doesn’t ingest data (that’s Fivetran, Airbyte, or your own loaders) and it doesn’t orchestrate the wider pipeline (that’s Airflow, Dagster, or dbt Cloud schedules).
dbt comes in two flavors. dbt Core is the open-source CLI you install with pip and run yourself. dbt Cloud is the managed platform on top of it — hosted IDE, job scheduling, CI, and docs hosting. Everything in this guide works in both; the code is identical, only the runtime differs.
Core Concepts
Before touching code, anchor the vocabulary. Every dbt project is built from the same handful of primitives:
Model: A SQL SELECT statement that dbt compiles into a table or view
Source: A reference to a table in your warehouse that dbt reads from
Seed: A CSV file loaded into your warehouse as a table (for static reference data)
Snapshot: Type 2 Slowly Changing Dimension — tracks history of changing rows
Test: A SQL assertion that returns rows that shouldn't exist (failing test)
Macro: A reusable Jinja code block for SQL generation
Materialization: How a model is stored (view, table, incremental, ephemeral)
Ref: A function to reference another model, building the dependency graph
Schema.yml: Configuration file defining sources, models, tests, and documentation
Two of these do the heavy lifting. ref() isn’t just a name resolver — every ref() call is an edge in the DAG (directed acyclic graph) that dbt builds from your models. The DAG is what lets dbt run models in the right order, parallelize siblings, and document lineage. source() is the counterpart for raw tables: declared once in YAML, it also powers freshness monitoring.
Project Structure
dbt projects follow a layered convention that keeps raw data, transformations, and business logic cleanly separated:
dbt_project/
├── dbt_project.yml # Project configuration
├── profiles.yml # Warehouse connection (usually in ~/.dbt/)
├── models/
│ ├── staging/ # Raw → clean (1:1 with source tables)
│ │ ├── stg_orders.sql
│ │ ├── stg_customers.sql
│ │ ├── sources.yml
│ │ └── schema.yml
│ ├── intermediate/ # Join and transform staging models
│ │ ├── int_orders_enriched.sql
│ │ └── schema.yml
│ ├── marts/ # Business-facing models
│ │ ├── core/
│ │ │ ├── fct_orders.sql
│ │ │ ├── dim_customers.sql
│ │ │ └── schema.yml
│ │ └── finance/
│ │ ├── fct_revenue.sql
│ │ └── schema.yml
├── macros/ # Reusable Jinja macros
│ ├── cents_to_dollars.sql
│ └── date_spine.sql
├── seeds/ # CSV files loaded as tables
│ └── country_codes.csv
├── snapshots/ # SCD Type 2 snapshots
│ └── snap_customers.sql
├── tests/ # Custom data tests
│ └── assert_positive_revenue.sql
├── analyses/ # One-off SQL analyses (not materialized)
└── packages.yml # External dbt packages
Two files control everything. dbt_project.yml defines the project name, paths, and defaults you can apply per directory — setting +materialized and +schema at folder level beats repeating config in every file:
# dbt_project.yml
name: analytics
version: '1.0.0'
profile: analytics
model-paths: ["models"]
seed-paths: ["seeds"]
macro-paths: ["macros"]
test-paths: ["tests"]
target-path: "target"
models:
analytics:
staging:
+materialized: view
+schema: staging
intermediate:
+schema: intermediate
marts:
+materialized: table
+schema: marts
profiles.yml holds the warehouse connection. It lives in ~/.dbt/ (outside the repo) so credentials never reach version control. The target selects which environment you’re building:
# ~/.dbt/profiles.yml
analytics:
target: dev
outputs:
dev:
type: snowflake
account: acme.us-east-1
user: dbt_dev
password: "{{ env_var('DBT_SNOWFLAKE_PASSWORD') }}"
role: transformer
warehouse: compute_wh
database: analytics_dev
schema: dbt_dev
threads: 4
prod:
type: snowflake
account: acme.us-east-1
user: dbt_prod
password: "{{ env_var('DBT_SNOWFLAKE_PASSWORD') }}"
role: transformer
warehouse: compute_wh
database: analytics_prod
schema: analytics
threads: 8
Models
A model is a single .sql file containing one SELECT statement — no DDL, no stored procedures, just a query dbt wraps with the right CREATE statement. The layering convention is where projects live or die:
- Staging (
stg_): one model per source table. Rename columns, cast types, trim strings — and nothing else. No joins, no business logic. - Intermediate (
int_): joins and complex transformations between staging and marts. Where the hard work happens. - Marts (
fct_/dim_): what analysts and dashboards actually query. Facts for events and measurements, dimensions for entities.
Staging models
-- models/staging/stg_orders.sql — Clean raw data
SELECT
order_id,
customer_id,
CAST(created_at AS TIMESTAMP) AS created_at,
CAST(updated_at AS TIMESTAMP) AS updated_at,
CAST(subtotal AS DECIMAL(10, 2)) AS subtotal,
CAST(tax AS DECIMAL(10, 2)) AS tax,
CAST(shipping AS DECIMAL(10, 2)) AS shipping,
TRIM(status) AS status,
TRIM(currency) AS currency
FROM {{ source('raw', 'orders') }}
WHERE order_id IS NOT NULL
The {{ source('raw', 'orders') }} call needs a sources.yml declaring what “raw” means — and optionally freshness rules that let dbt alert when upstream loaders fall behind:
# models/staging/sources.yml
version: 2
sources:
- name: raw
database: raw
schema: public
tables:
- name: orders
loaded_at_field: _loaded_at
freshness:
warn_after: { count: 12, period: hour }
error_after: { count: 24, period: hour }
- name: customers
- name: payments
Intermediate models
-- models/intermediate/int_orders_enriched.sql — Join staging models
SELECT
o.order_id,
o.customer_id,
o.created_at,
o.status,
o.subtotal + o.tax + o.shipping AS total_amount,
c.country,
c.customer_tier,
CASE
WHEN c.customer_tier = 'premium' THEN 0.10
WHEN c.customer_tier = 'gold' THEN 0.05
ELSE 0.00
END AS discount_rate
FROM {{ ref('stg_orders') }} o
LEFT JOIN {{ ref('stg_customers') }} c
ON o.customer_id = c.customer_id
Mart models (fact and dimension)
-- models/marts/core/dim_customers.sql — Dimension table
{{ config(materialized='table') }}
SELECT
customer_id,
first_name,
last_name,
email,
country,
customer_tier,
created_at,
COALESCE(first_order_date, '2099-12-31') AS first_order_date
FROM {{ ref('stg_customers') }}
LEFT JOIN (
SELECT
customer_id,
MIN(created_at) AS first_order_date
FROM {{ ref('stg_orders') }}
GROUP BY 1
) first_orders USING (customer_id)
-- models/marts/core/fct_orders.sql — Fact table
{{ config(materialized='incremental', unique_key='order_id') }}
SELECT
o.order_id,
o.customer_id,
o.created_at,
o.status,
o.total_amount,
o.discount_rate,
ROUND(o.total_amount * (1 - o.discount_rate), 2) AS net_amount,
d.country,
d.customer_tier
FROM {{ ref('int_orders_enriched') }} o
LEFT JOIN {{ ref('dim_customers') }} d
ON o.customer_id = d.customer_id
{% if is_incremental() %}
WHERE o.created_at > (SELECT MAX(created_at) FROM {{ this }})
{% endif %}
The is_incremental() guard is the subtle part: on the first run {{ this }} doesn’t exist yet, so the WHERE clause is skipped and the full history loads. On later runs only new rows are appended or merged. For a worked, runnable dbt model see the dbt model transformations recipe.
Materializations
Materialization controls how a model lands in the warehouse. Choosing wrong is the most common cause of slow dbt projects:
-- View (default): compiled SQL as a view in the warehouse
{{ config(materialized='view') }}
-- Table: materialized as a physical table (rebuilt on every run)
{{ config(materialized='table') }}
-- Incremental: only insert new rows since last run
{{ config(
materialized='incremental',
unique_key='order_id',
incremental_strategy='merge' -- or 'append', 'delete+insert'
) }}
-- Ephemeral: not materialized, inlined into dependent models as CTEs
{{ config(materialized='ephemeral') }}
| Materialization | Build cost | Data freshness | Best for |
|---|---|---|---|
view | ~zero | Always current | Staging, fast-changing data |
table | Full rebuild each run | Per run | Dimensions, small marts |
incremental | Delta only | Per run | Large facts, event tables |
ephemeral | Inlined downstream | — | Tiny reused transformations |
Incremental strategies
-- Append: fastest, but duplicates if source has updates
{{ config(materialized='incremental', incremental_strategy='append') }}
SELECT * FROM {{ source('raw', 'events') }}
{% if is_incremental() %}
WHERE event_time > (SELECT MAX(event_time) FROM {{ this }})
{% endif %}
-- Merge: upsert based on unique_key (no duplicates)
{{ config(materialized='incremental', unique_key='order_id', incremental_strategy='merge') }}
SELECT * FROM {{ ref('stg_orders') }}
{% if is_incremental() %}
WHERE created_at > (SELECT MAX(created_at) FROM {{ this }})
{% endif %}
-- Delete+insert: delete the partition, then insert fresh data
{{ config(
materialized='incremental',
incremental_strategy='delete+insert',
partition_by={'field': 'created_at', 'data_type': 'date'}
) }}
SELECT * FROM {{ ref('stg_orders') }}
{% if is_incremental() %}
WHERE created_at >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)
{% endif %}
Two gotchas worth knowing early. ephemeral pushes compute into every downstream model — fine for small logic, painful when an ephemeral model wraps a heavy join that then compiles into ten other queries (and some warehouses hit CTE limits). And incremental models drift silently when upstream schemas change; rebuild them periodically with dbt run --full-refresh after any source change.
Tests
dbt tests are SQL queries that should return zero rows. If a test query returns anything, the test fails. There are two kinds: generic tests declared in YAML against columns, and singular tests written as standalone SQL files.
Schema tests
# models/staging/schema.yml
version: 2
models:
- name: stg_orders
description: Orders cleaned and typed from the raw source
columns:
- name: order_id
tests:
- unique
- not_null
- name: customer_id
tests:
- not_null
- relationships:
to: ref('stg_customers')
field: customer_id
- name: status
tests:
- accepted_values:
values: ['pending', 'processing', 'shipped', 'completed', 'cancelled']
- name: total_amount
tests:
- dbt_utils.expression_is_true:
expression: ">= 0"
- name: stg_customers
columns:
- name: customer_id
tests:
- unique
- not_null
- name: email
tests:
- not_null
- unique
The four built-in generics (unique, not_null, accepted_values, relationships) cover most needs; the dbt_utils and dbt_expectations packages add dozens more, like range checks:
- name: discount_rate
tests:
- dbt_expectations.expect_column_values_to_be_between:
min_value: 0
max_value: 1
Custom singular tests
-- tests/assert_positive_revenue.sql — Custom test
SELECT
order_id,
total_amount
FROM {{ ref('fct_orders') }}
WHERE total_amount < 0
-- If any rows return, the test fails
-- tests/assert_no_duplicate_daily_revenue.sql
SELECT
order_date,
region,
COUNT(*) as duplicate_count
FROM {{ ref('fct_daily_revenue') }}
GROUP BY 1, 2
HAVING COUNT(*) > 1
Two config knobs make tests production-ready instead of decorative. +store_failures: true materializes the failing rows so you can inspect them directly. +severity: warn keeps flaky non-critical tests from blocking a deploy:
# dbt_project.yml
tests:
+store_failures: true
+severity: warn
Tests and observability are two sides of the same coin — for the wider quality framework (metrics, SLAs, monitoring) see the Complete Guide to Data Quality.
Macros
Macros are Jinja functions that generate SQL — the DRY escape hatch for patterns you’d otherwise copy-paste.
Reusable transformations
-- macros/cents_to_dollars.sql
{% macro cents_to_dollars(column_name) %}
ROUND({{ column_name }} / 100.0, 2)
{% endmacro %}
-- Usage in a model
SELECT
order_id,
{{ cents_to_dollars('subtotal_cents') }} AS subtotal,
{{ cents_to_dollars('tax_cents') }} AS tax
FROM {{ source('raw', 'orders') }}
Date spine macro
-- macros/date_spine.sql
{% macro date_spine(start_date, end_date, datepart='day') %}
WITH RECURSIVE date_spine AS (
SELECT DATE('{{ start_date }}') AS date_day
UNION ALL
SELECT DATE_ADD(date_day, INTERVAL 1 {{ datepart }})
FROM date_spine
WHERE date_day < DATE('{{ end_date }}')
)
SELECT date_day FROM date_spine
{% endmacro %}
-- Usage
SELECT * FROM ({{ date_spine('2026-01-01', '2026-12-31') }}) AS dates
Macro for safe division
-- macros/safe_divide.sql
{% macro safe_divide(numerator, denominator, default=0) %}
CASE
WHEN {{ denominator }} = 0 OR {{ denominator }} IS NULL THEN {{ default }}
ELSE {{ numerator }} / {{ denominator }}
END
{% endmacro %}
-- Usage
SELECT
region,
{{ safe_divide('revenue', 'order_count', 'NULL') }} AS avg_order_value
FROM {{ ref('fct_daily_revenue') }}
When a macro needs to work across warehouses, dbt ships adapter.dispatch — it resolves dialect-specific implementations at compile time, which is exactly how dbt_utils supports every adapter. Reach for it before writing IF warehouse == 'snowflake' logic in your macros.
Seeds
Seeds load CSV files into the warehouse as regular tables with dbt seed. They’re for small, static reference data — country codes, tax rates, mapping tables — that belongs in version control rather than a warehouse table someone keeps up by hand:
# seeds/country_codes.csv
country_code,country_name,region
US,United States,North America
CA,Canada,North America
UK,United Kingdom,Europe
DE,Germany,Europe
FR,France,Europe
JP,Japan,Asia
-- Usage in a model
SELECT
o.order_id,
c.country_name,
c.region
FROM {{ ref('stg_orders') }} o
JOIN {{ ref('country_codes') }} c
ON o.country_code = c.country_code
Keep seeds small (a few hundred rows, under ~1MB). Anything bigger belongs in a proper loader, not a CSV committed to git.
Snapshots
Snapshots implement SCD Type 2: when a source row changes, dbt closes the current record and inserts a new one, keeping dbt_valid_from / dbt_valid_to columns so you can query history:
-- snapshots/snap_customers.sql — Track changes to customer data
{% snapshot snap_customers %}
{{
config(
target_schema='snapshots',
unique_key='customer_id',
strategy='timestamp',
updated_at='updated_at',
)
}}
SELECT
customer_id,
first_name,
last_name,
email,
customer_tier,
updated_at
FROM {{ source('raw', 'customers') }}
{% endsnapshot %}
-- Query snapshot history
SELECT
customer_id,
customer_tier,
dbt_valid_from,
dbt_valid_to,
CASE WHEN dbt_valid_to IS NULL THEN 'current' ELSE 'historical' END AS record_status
FROM {{ ref('snap_customers') }}
WHERE customer_id = '12345'
ORDER BY dbt_valid_from
Two strategies exist. timestamp uses an updated_at column from the source — reliable when the loader keeps it fresh. check hashes a column list and detects any change — the fallback when sources lack a timestamp, at the cost of hashing every row. If a table is append-only (events, logs), you don’t need a snapshot at all; history is already there.
Jinja Templating
Jinja is what turns SQL into a programming language inside dbt — conditionals, loops, variables, and access to the runtime context:
-- Conditional logic
{% if var('is_production', false) %}
WHERE status = 'completed'
{% else %}
WHERE status IN ('completed', 'pending')
{% endif %}
-- Loops
{% set payment_methods = ['credit_card', 'bank_transfer', 'paypal'] %}
SELECT
order_id,
{% for method in payment_methods %}
SUM(CASE WHEN payment_method = '{{ method }}' THEN amount ELSE 0 END)
AS {{ method }}_amount
{% if not loop.last %},{% endif %}
{% endfor %}
FROM {{ ref('stg_payments') }}
GROUP BY 1
-- Variables (override at runtime: dbt run --vars '{"start_date": "2026-11-01"}')
{% set start_date = var('start_date', '2026-01-01') %}
WHERE created_at >= '{{ start_date }}'
-- Environment-aware configs
{{ config(
materialized='incremental',
schema='analytics' if target.name == 'prod' else 'analytics_dev',
tags=['prod'] if target.name == 'prod' else ['dev'],
) }}
Useful context at compile time: target.name for environment branching, var() for run-time parameters with defaults, env_var() for secrets (never hardcode credentials — even in macros), and run_started_at for time-based logic.
Running dbt in Development and CI
The core commands are few, but the selection syntax is where daily productivity lives:
dbt deps # Install packages.yml dependencies
dbt seed # Load CSV seeds into the warehouse
dbt run # Build all models
dbt test # Run all tests
dbt build # Run + test in DAG order (recommended)
dbt snapshot # Run SCD Type 2 snapshots
dbt docs generate # Generate documentation site
dbt docs serve # Serve docs with lineage graph
dbt source freshness # Check raw table freshness
dbt run --full-refresh # Rebuild incremental models from scratch
Node selection uses + for graph traversal — model+ means “this model and everything downstream”, +model means “this model and everything upstream”:
dbt run --select stg_orders+ # stg_orders and all dependents
dbt run --select +fct_orders # fct_orders and all parents
dbt run --select tag:staging # Models tagged 'staging'
dbt test --select marts # Tests on marts directory
For CI, state:modified+ with --defer is the standard pattern (“Slim CI”): dbt compares your PR’s manifest against production artifacts, and builds only what changed plus its children — minutes instead of hours:
dbt build --select state:modified+ --defer --state prod_artifacts/
Production Patterns
A few patterns separate hobby projects from reliable dbt deployments:
- Schema separation by target. Dev builds write to
dbt_devoranalytics_dev, prod writes toanalytics— same code, isolated byprofiles.ymltargets. Developers never touch prod data. dbt buildin CI on every PR. Withstate:modified+you only build changed models, catching bad SQL and failing tests before merge.- Scheduling the T step only. dbt transforms inside the warehouse; ingestion and cross-system orchestration stay upstream. Schedule dbt runs via dbt Cloud jobs, Apache Airflow (DbtCloudJobOperator or Cosmos), or a plain cron job on dbt Core.
- Packages instead of reinvention.
dbt_utils,dbt_expectations, and adapter-specific packages solve most macros you’d write yourself:
# packages.yml
packages:
- package: dbt-labs/dbt_utils
version: 1.3.0
- package: calogica/dbt_expectations
version: 0.10.0
- Docs as a deployment artifact.
dbt docs generateproduces a searchable site with the lineage graph — ship it to S3/Netlify alongside your data, don’t leave it on a laptop. - Freshness as monitoring.
dbt source freshnessfailing is an upstream ingestion problem, not a dbt problem — alert on it separately from test failures.
Best Practices
- Follow the staging → intermediate → marts layering — each layer has a clear purpose
- Use
ref()for all model references — dbt builds the dependency graph automatically - Name staging models
stg_, intermediateint_, factsfct_, dimensionsdim_ - Test every model — at minimum
uniqueandnot_nullon primary keys - Use incremental materialization for large fact tables — avoid full rebuilds
- Use
ephemeralmaterialization for small intermediate models — saves storage - Document every model and column in
schema.yml—dbt docs servegenerates docs - Use macros for repeated SQL patterns — DRY principle for SQL
- Use snapshots for SCD Type 2 — track history of changing source data
- Set
+store_failures: truein tests — query failing rows for debugging - Use
--select state:modified+in CI — only test what changed - Version your dbt project with git — same branching strategy as application code
Common Mistakes
- Not using
ref(): hardcoding table names breaks the dependency graph and materialization order. - Overusing
tablematerialization: views are cheaper for staging models that change frequently. - No tests on primary keys: duplicate or null IDs break downstream joins silently.
- Incremental without
unique_key: append strategy creates duplicates when source rows update. - Complex logic in marts: business logic should be in intermediate models, marts should be simple joins.
- Not using
is_incremental()guard: without the guard, incremental models do full rebuilds every run. - Testing only in production: if a broken model reaches
dbt buildin prod, your CI was decorative. Rundbt build --select state:modified+on every PR. SELECT *in staging models: explicit column lists make schema changes visible instead of silently swallowing new columns.
See Also
- dbt project companion on GitHub — runnable mini project with models, tests, macros, seeds, and snapshots
- dbt official documentation
- Complete Guide to Data Pipeline Architecture
- Complete Guide to Data Quality
- dbt model transformations recipe
Frequently Asked Questions
What is dbt?
dbt (data build tool) is a SQL-first transformation tool. You write SELECT statements as models, and dbt compiles them into views/tables in your warehouse, managing dependencies, testing, and documentation.
What are materializations?
How dbt stores a model in the warehouse. view creates a view, table creates a physical table (rebuilt each run), incremental only adds new rows, and ephemeral inlines the model as a CTE into dependent models without materializing.
What is the difference between sources and refs?
source() references a raw table that exists in your warehouse before dbt runs. ref() references another dbt model. ref() builds the dependency graph — dbt knows to run the referenced model first.
What are dbt tests?
SQL assertions that return rows that shouldn't exist. unique tests that no values repeat. not_null tests that no values are null. relationships tests referential integrity. If a test returns any rows, it fails.
What is a snapshot in dbt?
A Type 2 Slowly Changing Dimension. dbt tracks changes to source rows over time, maintaining dbt_valid_from and dbt_valid_to columns. This lets you query what a row looked like at any point in time.
What is the difference between dbt Core and dbt Cloud?
dbt Core is the open-source CLI — free, pip-installable, run anywhere. dbt Cloud is the managed SaaS on top of it: hosted IDE, job scheduling, CI integration, and documentation hosting. Projects are portable between them.
When should I use incremental instead of table?
When the model is large and mostly append-driven — event tables, order facts, logs — and a full rebuild would be slow or expensive. If a model is small or queries change often, keep table; incremental adds complexity and needs periodic --full-refresh runs to stay honest.
How does dbt know if my source data is fresh?
Through loaded_at_field and freshness thresholds in sources.yml. dbt source freshness compares each raw table's load timestamp against your warn_after/error_after limits — a lightweight check that catches broken upstream loaders before bad data reaches your marts.
Related Resources
Data Pipeline Architecture: Batch, Streaming, Lambda, Kappa
Design batch and streaming data pipelines — working Airflow, Flink and dbt code, Lambda vs Kappa trade-offs, and a decision table for ETL vs ELT.
GuideApache Airflow: DAGs, Operators, Scheduling
Master Apache Airflow: DAGs, operators, sensors, XCom, scheduling, backfilling, connections, variables, and production patterns for data pipelines.
GuideData Quality Guide: Validation, Profiling, Monitoring
Master data quality: validation frameworks, profiling, schema enforcement, anomaly detection, and pipeline checks with Great Expectations, Pandera, and Soda.
RecipeTransform Data in the Warehouse with dbt
How to use dbt for SQL-based data transformations with models, tests, materializations, macros, and incremental loading in a data warehouse.
DocData Pipeline Design Document Template
A template for documenting data pipeline sources, transformations, sinks, scheduling, error handling, and monitoring with schema definitions.
GuideComplete Guide to SQL Query Optimization
Find and fix slow SQL queries: read EXPLAIN plans, index the right way, kill N+1 queries, and apply partitioning, pooling, and caching on PostgreSQL and MySQL.