Transforming Data with dbt
Writing modular SQL models with ref(), tests, documentation and incremental materialisations using dbt.
Intermediate · about 10 hours · difficulty 3/5
Learn first: ETL, ELT and the Modern Data Stack, Git and GitHub for Analysts, Subqueries and CTEs
dbt (data build tool) lets analysts transform data with plain SQL SELECT statements while adding software practices: dependencies, testing, documentation and version control. It is the core skill of analytics engineering.
Models and ref()
A model is a .sql file containing a SELECT. dbt turns it into a view or table. Models reference each other with ref(), which builds the dependency graph:
-- models/marts/fct_orders.sql
select o.order_id, o.customer_id, o.ordered_at, p.amount
from {{ ref('stg_orders') }} o
join {{ ref('stg_payments') }} p using (order_id)
Raw tables are declared as sources and referenced with source('shop', 'orders').
Materialisations
- view: default, always fresh, computed at query time.
- table: rebuilt each run, fast to query.
- incremental: only processes new rows, for large event tables.
- ephemeral: inlined as a CTE.
Tests and docs
In YAML you declare tests such as unique, not_null, accepted_values and relationships, plus column descriptions. dbt build runs models and tests together; dbt docs generate produces a browsable site with lineage.
Jinja and macros
Jinja templating adds loops and reusable macros, for example generating a pivot for every payment method. Use sparingly; readable SQL beats clever SQL.
Pitfall: putting business logic into staging models or copying the same CASE statement into many models. Centralise it in one intermediate model. You are ready to move on when you can build the dbt Jaffle Shop project with staging and mart models, tests and generated docs.
Key concepts
- Models, sources and ref()
- Project structure and naming
- Materialisations
- Generic and singular tests
- Documentation and lineage
- Incremental models
- Jinja and macros
- Semantic layer and metrics
Mini project
Complete the dbt Jaffle Shop tutorial on DuckDB or BigQuery, then add a customer lifetime value mart with unique and not_null tests and column descriptions.
Check yourself
What does ref() give you that hard-coding a table name does not?
Free resources
- dbt documentation (dbt Labs)
- dbt Learn free courses (dbt Labs)