(updated )5 min readBeginner§ dbt

dbt Tutorial: Build Your First Transformation Project the Right Way

Set up a dbt project from scratch: staging models, marts, tests, and documentation, with the project structure conventions used by real teams.

By Dinesh ChandraSenior Data and AI Engineer · SnowPro certified
Illustrated overview of dbt Tutorial: Build Your First Transformation Project the Right Way
Fig. 1 · dbt
  1. 1.Staging models stay 1:1 with sources; marts are the business grain.
  2. 2.Tests and documentation ship with dbt build, not as an afterthought.
  3. 3.Selectors and state comparison keep CI cheap as the project grows.
Table of contents

dbt turned SQL transformation into software engineering: version control, tests, documentation, and dependency management. Here’s how to start a project you won’t regret in six months.

flowchart LR
  src[Sources] --> stg[Staging models]
  stg --> int[Intermediate]
  int --> marts[Marts / Gold]
  marts --> tests[Tests + docs]

Install and initialize

pip install dbt-duckdb   # or dbt-snowflake, dbt-bigquery, dbt-postgres...
dbt init my_analytics

We’ll use DuckDB locally; the workflow is identical on a cloud warehouse.

Declare the raw relation so freshness and lineage have an owner:

# models/staging/_sources.yml
sources:
  - name: shop
    tables:
      - name: raw_orders
        freshness:
          warn_after: { count: 12, period: hour }
          error_after: { count: 24, period: hour }
        loaded_at_field: _loaded_at

source() is the extract you do not own. ref() is a model in your DAG. Mixing them hides who you page when the data is stale.

The structure that scales

The convention used by most serious dbt teams has two layers:

models/
  staging/          -- 1:1 with source tables; rename, cast, clean ONLY
    stg_orders.sql
    stg_customers.sql
  marts/            -- business logic; what analysts actually query
    fct_orders.sql
    dim_customers.sql

Staging models do nothing clever:

-- models/staging/stg_orders.sql
select
    id            as order_id,
    customer_id,
    status,
    amount_cents / 100.0  as amount,
    created_at::timestamp as ordered_at
from {{ source('shop', 'raw_orders') }}

Marts contain the business logic, built only from staging models:

-- models/marts/fct_orders.sql
select
    o.order_id,
    o.ordered_at,
    o.amount,
    c.customer_name,
    c.first_order_date,
    o.amount > 100 as is_large_order
from {{ ref('stg_orders') }} o
join {{ ref('stg_customers') }} c using (customer_id)
where o.status != 'cancelled'

ref() is the magic: dbt builds the dependency graph from it, runs models in the right order, and parallelizes what it can.

Tests: two lines that save your weekend

# models/marts/_marts.yml
models:
  - name: fct_orders
    columns:
      - name: order_id
        data_tests: [unique, not_null]
      - name: amount
        data_tests:
          - dbt_utils.accepted_range:
              min_value: 0

dbt test now fails your pipeline before bad data reaches a dashboard. This is the single highest-value feature of dbt; use it from day one.

Run it

dbt run    # builds all models in dependency order
dbt test   # runs all tests
dbt docs generate && dbt docs serve  # interactive lineage graph

Three habits of healthy dbt projects

  1. Nothing queries raw tables except staging models. Enforce it in code review.
  2. Every mart has at least unique + not_null tests on its key.
  3. Materialize marts as tables, staging as views; set it once in dbt_project.yml.
# dbt_project.yml
models:
  my_analytics:
    staging:
      +materialized: view
    marts:
      +materialized: table

Add an intermediate model the first time two marts copy the same five-join block. Do not paste it a third time.

flowchart TD
  raw[source shop.raw_orders] --> stg[stg_orders]
  rawc[source shop.raw_customers] --> stgc[stg_customers]
  stg --> fct[fct_orders]
  stgc --> fct
  fct --> test[unique + not_null]

Sources stay at the edge. Marts only ref models.

Profiles and the first real warehouse

DuckDB is the laptop. Prod is a profile you do not keep in git.

# ~/.dbt/profiles.yml  — not in the repo
my_analytics:
  target: dev
  outputs:
    dev:
      type: duckdb
      path: dev.duckdb
    prod:
      type: snowflake
      account: "{{ env_var('SNOWFLAKE_ACCOUNT') }}"
      user: "{{ env_var('DBT_USER') }}"
      private_key_path: "{{ env_var('DBT_KEY') }}"
      database: ANALYTICS
      schema: dbt_{{ env_var('USER') }}
      warehouse: TRANSFORM_M

Dev writes a personal schema. CI writes a PR schema. Prod writes ANALYTICS through a service user. Sharing one schema named PUBLIC is how a laptop dbt run overwrites a mart.

packages.yml for dbt_utils belongs in the repo. The profile does not.

Documentation is a model property

models:
  - name: fct_orders
    description: One row per placed order. Grain is order_id.
    columns:
      - name: order_id
        description: Source shop.raw_orders.id
        data_tests: [unique, not_null]

If you cannot say the grain in one sentence, the model is not ready. dbt docs is how a new teammate finds that sentence. Empty descriptions are how tribal knowledge returns.

Hub: dbt. Next depth: incremental models and slim CI.

Incremental when the mart grows

A full refresh of a fact is fine until it is not. Then you need a key or a replaceable partition:

-- models/marts/fct_orders.sql
{{ config(
    materialized='incremental',
    unique_key='order_id',
    incremental_strategy='merge'
) }}

select ...
from {{ ref('stg_orders') }}
{% if is_incremental() %}
  where ordered_at >= (select max(ordered_at) from {{ this }})
{% endif %}

Without a unique key, incremental is append. A retry will duplicate yesterday.

Slim CI, briefly

dbt build --select state:modified+ --defer --state path/to/prod-manifest

CI writes to a PR schema. It should not rebuild the warehouse or write prod. You need a prod manifest.json artifact for modified+ to mean anything.

Mistakes that show up in month three

  • Business logic in staging. Staging is rename, type, and light clean. Grain and metrics live in marts (or a thin int_ layer).
  • ref to a source. Use source() in staging only. Everything else ref()s a model so lineage stays honest.
  • CI that runs the whole project. Use a slim CI selector (state:modified+) once you have a prod manifest.
  • No freshness on sources. A silent stale extract looks like a dbt bug. Add freshness on the tables you cannot afford to miss.

FAQ

Why did unique fail on fct_orders? The grain is broken. GROUP BY order_id HAVING count(*) > 1, then fix the join, do not DISTINCT the fact.

Can staging have 12 joins? No. Staging is 1:1 with a source. Shared join logic is an intermediate model.

Should CI run dbt run or dbt build? build, since it runs models and tests. run will ship a broken key.

When do I snapshot? When you need Type-2 history of a source you do not control. Owned dims with valid_from / valid_to are better when facts must join as-of.

Is ephemeral a free refactor? Ephemeral inlines as a CTE. Fine for tiny logic. A 20-join ephemeral compiled into every mart is how CI gets sad.

What this means for your pipelines

A sources.yml with freshness on every extract you cannot afford to miss. Staging 1:1 with those sources. One fact and two dims in marts/ with unique and not_null on the grain. dbt build in CI, not dbt run. A prod manifest.json artifact as soon as the second person opens a PR, so slim CI is possible.

Do not add a semantic layer, a 40-model DAG, or a custom materialization in week one. Add an owner on the fact (meta.owner) so the first red unique test pages a human. Policy for fail-versus-ticket is in data quality. Project layout at scale is in dbt project structure. Hub: dbt.

Next: data quality in Python and SQL windows.

Share this post:X / TwitterLinkedInRedditWhatsApp
D

Dinesh Chandra

Senior Data & AI Engineer · SnowPro Core & Gen AI Certified

4+ years building production data platforms on Snowflake, Databricks, AWS, and Azure. I write from hands-on experience with Medallion architectures, dbt, Airflow, PySpark, and Snowflake Cortex AI. Every tutorial on this blog reflects real pipeline decisions, not documentation rewrites.

Read more about the author →
RE

Related entries

§ dbtIntermediate
Illustrated overview of dbt Microbatch: Incremental Models Built by Time Batch

· 8 min

dbt Microbatch: Incremental Models Built by Time Batch

How the dbt microbatch strategy works: event_time, batch_size, lookback, targeted backfills, retrying failed batches, and when it beats a hand-written filter.

  • #dbt
  • #incremental-models
§ dbtIntermediate
Illustrated overview of dbt Model Contracts and Versions for Shared Models

· 9 min

dbt Model Contracts and Versions for Shared Models

Use dbt model contracts, versions, access levels and deprecation dates to change a widely used model without breaking the dashboards and teams that use it.

  • #dbt
  • #data-contracts
  • #governance

Search DataLane

↑↓ navigatealt ↑↓ jump group↵ openesc close