The one-line mental model
dbt turns SQL SELECT statements into a versioned, tested, documented transformation layer: staging models clean one source table each, intermediate models reshape, and mart models serve business-ready tables â all orchestrated by a DAG that runs only what changed.
You will be able to:
- Structure a dbt project into staging, intermediate, and mart layers
- Choose materializations (table, view, incremental, ephemeral) per model
- Write generic and singular tests that gate data quality in CI
- Generate and publish documentation with lineage graphs
Prerequisites
- !Comfortable writing SELECT, JOIN, and window functions
- !Basic Git workflow (branch, commit, pull request)
- !Familiarity with at least one SQL warehouse (Snowflake, BigQuery, Postgres)
What You'll Learn
- 1Explain why analytics engineering sits between data engineering and BI
- 2Create a source definition and reference it in a staging model
- 3Build a mart model with a surrogate key and incremental materialization
- 4Run dbt build to compile, test, and run the DAG in dependency order
The layers of a dbt project
A well-organized dbt project follows a layered convention. Staging models are one-to-one with source tables: light renaming, type casting, and column selection â no joins. Intermediate models combine and reshape staging models. Marts are business-facing tables joined and aggregated for analysts and downstream tools. This layering keeps blast radius small: a change to a raw feed affects one staging model, not forty downstream queries.
| Layer | Scope | Materialization default | Naming pattern |
|---|---|---|---|
| Staging | One source table, light cleanup | view | stg_<source>__<table> |
| Intermediate | Reshaping, joining staging models | ephemeral or table | int_entity_action |
| Mart | Business-ready fact/dimension | table or incremental | fct_* / dim_* |
The double-underscore convention in staging names (for example stg_shopify__orders) maps directly to source and table, making lineage obvious from the filename alone.
Project layout and configuration
A fresh dbt init scaffolds models/, macros/, tests/, and dbt_project.yml. The project file sets model paths, default materializations, and variables. Sources are declared in YAML under models/ so the warehouse schema and freshness checks live next to the models that consume them.
Configuration hierarchy matters: project-level defaults apply everywhere unless overridden at the folder, model, or individual-config level. This lets a team set a sane global default (views for staging, tables for marts) and override it only where the workload demands it â a large fact table that would be prohibitively expensive as a view gets materialized='incremental' at the model level, while everything else inherits the project default. Variables declared in dbt_project.yml and overridden per-environment with --vars or profiles keep environment-specific values (start dates, feature flags, threshold parameters) out of hard-coded SQL, which is what makes the same codebase safe to run in development, CI, and production without conditional logic.
# dbt_project.yml
name: analytics
version: 1.0.0
profile: analytics
model-paths: ["models"]
macro-paths: ["macros"]
test-paths: ["tests"]
seed-paths: ["seeds"]
models:
analytics:
+materialized: view
staging:
+schema: staging
+materialized: view
marts:
+schema: marts
+materialized: table
vars:
start_date: '2024-01-01'
currency: 'USD'
# models/staging/sources.yml
version: 2
sources:
- name: raw_shopify
database: raw
schema: shopify
loaded_at_field: _s_loaded_at
freshness:
warn_after: {count: 12, period: hour}
error_after: {count: 24, period: hour}
tables:
- name: orders
- name: order_items
- name: customers
Freshness checks are the cheapest reliability win in the stack: dbt source freshness fails the build when a feed stops arriving before any downstream model silently serves stale numbers.
Staging and mart models
Staging models select only needed columns, cast types, and rename snake_case. Mart models join staging models, build surrogate keys with dbt_utils.generate_surrogate_key, and aggregate to the grain analysts query. Each model is a single SQL file; dbt compiles Jinja references (ref, source) into warehouse-specific SQL and resolves the DAG automatically.
-- models/staging/stg_shopify__orders.sql
{{ config(materialized='view') }}
select
id as order_id,
customer_id as customer_id,
cast(created_at as date) as order_date,
cast(total_price as numeric) as total_price,
currency,
lower(coalesce(status, 'unknown')) as order_status,
_s_loaded_at
from {{ source('raw_shopify', 'orders') }}
where _s_loaded_at >= '{{ var("start_date") }}'
-- models/staging/stg_shopify__order_items.sql
{{ config(materialized='view') }}
select
order_id,
sku,
product_title,
cast(quantity as integer) as quantity,
cast(price as numeric) as unit_price,
cast(quantity as numeric)
* cast(price as numeric) as line_total,
_s_loaded_at
from {{ source('raw_shopify', 'order_items') }}
-- models/marts/fct_orders.sql
{{ config(materialized='incremental',
unique_key='order_id',
on_schema_change='append_new_columns') }}
with orders as (
select * from {{ ref('stg_shopify__orders') }}
{% if is_incremental() %}
where _s_loaded_at > (select max(_loaded_at) from {{ this }})
{% endif %}
),
items as (
select
order_id,
sum(line_total) as item_revenue,
sum(quantity) as total_units,
count(*) as item_count
from {{ ref('stg_shopify__order_items') }}
group by 1
),
final as (
select
{{ dbt_utils.generate_surrogate_key(['o.order_id']) }} as order_sk,
o.order_id,
o.customer_id,
o.order_date,
o.total_price,
o.currency,
o.order_status,
coalesce(i.item_revenue, 0) as item_revenue,
coalesce(i.total_units, 0) as total_units,
coalesce(i.item_count, 0) as item_count,
current_timestamp() as _loaded_at
from orders o
left join items i on o.order_id = i.order_id
)
select * from final
Incremental materialization is the key performance lever: only new or changed rows are reprocessed, so a fact table covering years of history rebuilds in minutes instead of hours. The is_incremental() guard keeps the model a full rebuild on first run and a filtered append thereafter.
Tests as data contracts
dbt ships generic tests â unique, not_null, accepted_values, relationships â declared in YAML, plus singular tests that are custom SQL files returning failing rows. Together they act as data contracts: a PR that breaks a uniqueness or referential-integrity rule cannot merge.
# models/staging/schema.yml
version: 2
models:
- name: stg_shopify__orders
description: "Cleaned Shopify orders, one row per order."
columns:
- name: order_id
description: "Primary key, unique Shopify order identifier."
tests:
- unique
- not_null
- name: customer_id
tests:
- not_null
- relationships:
to: ref('stg_shopify__customers')
field: customer_id
- name: order_status
tests:
- accepted_values:
values: ['pending', 'paid', 'shipped',
'delivered', 'refunded', 'unknown']
- name: total_price
tests:
- not_null
- name: stg_shopify__order_items
columns:
- name: order_id
tests:
- relationships:
to: ref('stg_shopify__orders')
field: order_id
-- tests/assert_positive_line_totals.sql
-- Singular test: returns rows that violate the business rule
select
order_id,
sku,
line_total
from {{ ref('stg_shopify__order_items') }}
where line_total < 0
or quantity <= 0
Run dbt build to execute models and tests in dependency order; the DAG guarantees a failing test blocks downstream models from running, which is exactly the fail-fast behavior you want on a nightly schedule.
Macros for DRY logic
Jinja macros factor repeated SQL fragments â date spine generation, currency conversion, slowly-changing-dimension merge logic â into reusable, parameterized functions. A well-placed macro can collapse fifty lines of copy-pasted SQL across thirty models into one tested unit.
-- macros/currency_conversion.sql
{% macro convert_currency(amount_column, currency_column,
target_currency=var('currency')) %}
case
when {{ currency_column }} = {{ target_currency }}
then {{ amount_column }}
when {{ currency_column }} = 'USD'
then {{ amount_column }} * {{ target_rate('USD') }}
when {{ currency_column }} = 'EUR'
then {{ amount_column }} * {{ target_rate('EUR') }}
else {{ amount_column }}
end
{% endmacro %}
{% macro target_rate(src_currency) %}
{%- set rates = {'USD': 1.0, 'EUR': 1.08, 'GBP': 1.27} -%}
{{ rates.get(src_currency, 1.0) }}
{% endmacro %}
-- Usage inside a model
select
order_id,
{{ convert_currency('total_price', 'currency') }} as total_price_usd
from {{ ref('stg_shopify__orders') }}
Keep macros pure and small. When conversion logic grows into a slowly-changing rates table, swap the static dictionary for a ref() to a rates dimension â macros can call refs, and dbt tracks the added dependency in the DAG.
Documentation and lineage
dbt docs generate parses model descriptions, column-level comments, and the compiled DAG, then dbt docs serve hosts a local site where stakeholders click from table to table along the lineage graph. Writing the description: blocks as if the reader has never seen the schema pays compounding interest every time someone new joins the team.
Lineage is the killer feature for incident response. When a dashboard shows an unexpected number, the lineage graph answers "which upstream models feed this, and when did each last run?" in seconds â work that previously took hours of manual SQL spelunking through interdependent views. The same graph makes impact analysis trivial before a change: if you rename a column in a staging model, the downstream consumers light up immediately, so you know exactly which tests to run and which stakeholders to notify. Teams that invest in descriptions and tests find that the dbt docs site becomes the de facto data catalog, reducing ad-hoc Slack questions to the data team by a noticeable fraction within the first quarter of adoption.
# CLI workflow
dbt debug # verify warehouse connection
dbt deps # install packages (e.g. dbt_utils)
dbt source freshness # check feed lag against SLAs
dbt seed # load CSV reference data
dbt build --select +fct_orders+ # build fct_orders and its parents/children
dbt test --select fct_orders # run tests on one model
dbt docs generate
dbt docs serve # open http://localhost:8080
The +fct_orders+ selector syntax (plus signs on both sides) pulls upstream parents and downstream children â the right scope for validating a change before merge without rebuilding the entire warehouse.