iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔨

dbt for Beginners: Learn by Building Data Pipelines with DuckDB

に公開

What's This?

I created a data pipeline using dbt and DuckDB. This article explains the steps from loading CSV files to aggregating purchase summaries per customer, aimed at beginners.

Introduction

Since I had never touched dbt (data build tool), I went through a tutorial from scratch using Claude Code's learning mode.

In this article, I'll introduce the process of learning dbt's basic concepts by actually doing it hands-on.

What You'll Learn in This Article

  • Basic structure of a dbt project
  • Seeds (loading CSV data)
  • Creating Staging and Mart layers
  • How to use {{ source() }} and {{ ref() }}
  • Automatic dependency resolution

Environment

  • dbt-core: 1.10.13
  • dbt-duckdb: 1.9.6
  • DuckDB: 1.4.0
  • uv (Python package manager)

Environment Setup

1. Installing uv

First, install the fast Python package manager uv:

# macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

# Or with Homebrew
brew install uv

For Windows, refer to the official site.

2. Project Setup

Create the project directory and install the required packages:

# Create project directory
mkdir hello-dbt
cd hello-dbt

# Create pyproject.toml
cat > pyproject.toml << 'EOF'
[project]
name = "hello-dbt"
version = "0.1.0"
dependencies = [
    "dbt-core>=1.10.0",
    "dbt-duckdb>=1.9.6",
]
requires-python = ">= 3.11"
EOF

# Install dependencies
uv sync

This installs dbt-core and dbt-duckdb, ready to use.

3. How to Run dbt Commands

In this article, we run dbt commands using the uv run dbt format:

uv run dbt --version
# dbt-core: 1.10.13
# dbt-duckdb: 1.9.6

By prepending uv run, the virtual environment is automatically activated.

Setting Up a dbt Project

First, create the project structure:

mkdir -p myproject/{models/{staging,marts},seeds,tests,macros,snapshots,analyses}

dbt_project.yml

Create the project configuration file:

name: 'myproject'
version: '1.0.0'
config-version: 2

profile: 'myproject'

model-paths: ["models"]
seed-paths: ["seeds"]
test-paths: ["tests"]
macro-paths: ["macros"]
snapshot-paths: ["snapshots"]

clean-targets:
  - "target"
  - "dbt_packages"

~/.dbt/profiles.yml

Database connection settings:

myproject:
  outputs:
    dev:
      type: duckdb
      path: dev.duckdb
      threads: 1

  target: dev

Verify it works:

cd myproject
uv run dbt debug

If you see All checks passed!, everything is set up.

Step 1: Creating Sample Data with Seeds

In dbt, you can load development data by placing CSV files in the seeds/ directory.

seeds/raw_customers.csv

customer_id,first_name,last_name,email
1,John,Doe,john@example.com
2,Jane,Smith,jane@example.com
3,Bob,Johnson,bob@example.com
4,Alice,Williams,alice@example.com

seeds/raw_orders.csv

order_id,customer_id,order_date,amount
101,1,2025-01-15,250
102,2,2025-01-16,450
103,3,2025-01-17,300
104,4,2025-01-18,150
105,2,2025-01-19,500
106,1,2025-01-20,700
107,3,2025-01-21,200
108,4,2025-01-22,350
109,1,2025-01-23,400

Load the CSVs into DuckDB:

uv run dbt seed
Found 2 seeds, 444 macros
1 of 2 OK loaded seed file main.raw_customers ... [INSERT 4 in 0.04s]
2 of 2 OK loaded seed file main.raw_orders ...... [INSERT 9 in 0.01s]
Done. PASS=2 WARN=0 ERROR=0 SKIP=0 NO-OP=0 TOTAL=2

Verify the data:

duckdb dev.duckdb
SELECT * FROM raw_customers;

💡 What I Learned

  • dbt seed creates CSV files as tables
  • If the schema changes, you need --full-refresh to recreate
  • Not for production use, convenient for dev reference data

Step 2: Defining Sources

Before using {{ source() }}, you need to tell dbt about the source tables.

models/schema.yml

version: 2

sources:
  - name: main
    tables:
      - name: raw_customers
      - name: raw_orders

name: main is the DuckDB schema name.

💡 What I Learned

  • If you don't define sources in schema.yml, you cannot use {{ source() }}
  • dbt reads this file to understand data dependencies

Step 3: Creating Staging Models

In the Staging layer, we clean up the raw data.

models/staging/stg_customers.sql

-- Staging: Customer data
SELECT
  customer_id,
  first_name,
  last_name,
  email
FROM
  {{ source('main', 'raw_customers') }}

models/staging/stg_orders.sql

-- Staging: Order data
SELECT
  order_id,
  customer_id,
  order_date,
  amount
FROM
  {{ source('main', 'raw_orders') }}

Run the models:

uv run dbt run
Concurrency: 1 threads (target='dev')

1 of 2 START sql view model main.stg_customers ... [RUN]
1 of 2 OK created sql view model main.stg_customers [OK in 0.06s]
2 of 2 START sql view model main.stg_orders ....... [RUN]
2 of 2 OK created sql view model main.stg_orders ... [OK in 0.01s]

Done. PASS=2 WARN=0 ERROR=0 SKIP=0 NO-OP=0 TOTAL=2

Verify the schema in DuckDB:

duckdb dev.duckdb -c ".schema"
CREATE TABLE raw_customers(...);
CREATE TABLE raw_orders(...);
CREATE VIEW stg_customers AS SELECT ... FROM dev.main.raw_customers;
CREATE VIEW stg_orders AS SELECT ... FROM dev.main.raw_orders;

💡 What I Learned

  • dbt models are just SELECT statements
  • By default, they are created as VIEWs
  • Use {{ source('schema', 'table') }} to reference raw data
  • The Staging layer is used for unifying column names and type conversions

Step 4: Creating Mart Models

In the Mart layer, we JOIN multiple staging models to create data for business analysis.

models/marts/customer_summary.sql

-- Mart model: customer_summary.sql
SELECT
  c.customer_id,
  c.first_name || ' ' || c.last_name as full_name,
  c.email,
  COUNT(o.order_id) as total_orders,
  SUM(o.amount) as total_spent
FROM
  {{ ref('stg_customers') }} as c
LEFT JOIN
  {{ ref('stg_orders') }} as o
ON
  c.customer_id = o.customer_id
GROUP BY
  c.customer_id, c.first_name, c.last_name, c.email

Run the models:

uv run dbt run
Found 3 models, 2 seeds, 2 sources, 444 macros

1 of 3 START sql view model main.stg_customers ..... [RUN]
1 of 3 OK created sql view model main.stg_customers  [OK in 0.04s]
2 of 3 START sql view model main.stg_orders ........ [RUN]
2 of 3 OK created sql view model main.stg_orders ... [OK in 0.01s]
3 of 3 START sql view model main.customer_summary .. [RUN]
3 of 3 OK created sql view model main.customer_summary [OK in 0.01s]

Done. PASS=3 WARN=0 ERROR=0 SKIP=0 NO-OP=0 TOTAL=3

Check the results:

duckdb dev.duckdb -c "SELECT * FROM customer_summary ORDER BY customer_id;"
┌─────────────┬────────────────┬──────────────┬─────────────┐
│ customer_id │   full_name    │ total_orders │ total_spent │
├─────────────┼────────────────┼──────────────┼─────────────┤
│           1 │ John Doe       │            3 │        1350 │
│           2 │ Jane Smith     │            2 │         950 │
│           3 │ Bob Johnson    │            2 │         500 │
│           4 │ Alice Williams │            2 │         500 │
└─────────────┴────────────────┴──────────────┴─────────────┘

💡 What I Learned

  • Use {{ ref('model_name') }} to reference other dbt models
  • dbt automatically resolves dependencies and runs models in the correct order
  • When joining, use table aliases (e.g., c.customer_id = o.customer_id)
  • The Mart layer implements business logic (aggregations and joins)

How dbt's Dependency Mechanism Works

Looking at the execution log, you can see that dbt understands the dependencies:

1 of 3: stg_customers  ← First, customer data
2 of 3: stg_orders     ← Next, order data
3 of 3: customer_summary ← Finally, the summary (because it uses both)

It parses {{ ref() }} and automatically builds a DAG (Directed Acyclic Graph).

Overall Data Pipeline Architecture

[Seeds - Bronze Layer]
├── raw_customers.csv  → raw_customers (TABLE)
└── raw_orders.csv     → raw_orders (TABLE)
          ↓ {{ source() }}
[Staging - Silver Layer]
├── stg_customers.sql  → stg_customers (VIEW)
└── stg_orders.sql     → stg_orders (VIEW)
          ↓ {{ ref() }}
[Marts - Gold Layer]
└── customer_summary.sql → customer_summary (VIEW)

This is a design pattern called the Medallion Architecture:

  • Bronze Layer (Seeds): Store raw data as-is
  • Silver Layer (Staging): Clean up and standardize data
  • Gold Layer (Marts): Transform data for business analysis

Common Issues and Solutions

1. Source Not Found

Error: depends on a source named 'main.raw_customers' which was not found

→ Define the source in models/schema.yml

2. Column Not Found

Error: Referenced column "order_date" not found!
Candidate bindings: "order_data", ...

→ Check that the CSV column names match your SQL
→ If the schema changed, recreate with dbt seed --full-refresh

3. Ambiguous JOIN Condition

-- ❌ NG: It's unclear which customer_id is from which table
ON customer_id = customer_id

-- ✅ OK: Explicit with table aliases
ON c.customer_id = o.customer_id

Summary

The benefits of using dbt:

  1. You can build data pipelines with SQL alone - No Python code required (only the runtime is needed)
  2. Automatic dependency resolution - You don't have to worry about execution order
  3. Modularity - Split into small, reusable models
  4. Testing & documentation features - Ensure data quality

First Impressions

Being able to declaratively write SQL and have dbt seed or dbt run resolve dependencies and produce results was quite comfortable.

On the other hand, writing SQL by hand with Jinja template syntax felt a bit cumbersome. However, with a coding agent like Claude Code, this complexity might not be an issue.

Next Steps

  • Add data quality tests with dbt test
  • Auto-generate documentation with dbt docs generate
  • Use {{ config(materialized='table') }} to materialize as tables for performance
  • Handle large-scale data with incremental models

About Claude Code's Learning Mode

This article was created using Claude Code's "Learning Mode."

Characteristics of Learning Mode:

  • Hands-on learning: Rather than having AI do everything, you write code yourself at key points
  • Step-by-step explanations: Progress while understanding concepts one at a time
  • Practical guidance: Guidance on why you do things and how to write them

It was especially valuable to learn, through encountering actual errors, points that are hard to notice from documentation alone—such as "schema.yml is needed before using {{ source() }}" or "--full-refresh is required to re-run seeds.”

References

GitHubで編集を提案

Discussion