Why Transformations Belong in Version-Controlled SQL
Why hand-run scripts and stored procedures fail as a home for warehouse transformations, how dbt turns a folder of SELECT statements into tables, views and a dependency graph, and how sources, staging, intermediate and mart models divide the work.
Contentsand lesson path
On this page
- Why it matters
- A model is a SELECT; dbt writes the DDL
- ref() and source(): names that follow the environment
- Sources, staging, intermediate and marts
- Check your understanding
- Apply it
- Review prompt
Lessons of SQL Transformation with dbt
- Why Transformations Belong in Version-Controlled SQL Concept · 15 min
- Lab: Sources, Staging Models and the ref() Graph Lab · 30 min
- Materializations and Incremental Models Worked example · 25 min
- Snapshots, Macros and Keeping Jinja in Check Lab · 25 min
- Lab: Docs and dbt build in Pull-Request CI Lab · 25 min
- Check: Review a dbt Pull Request Knowledge check · 8 questions
What you will learn
- Structure a dbt project into sources, staging, intermediate and mart models linked with ref() and source(), and explain the resulting dependency graph.
Prerequisites: SQL Fundamentals
01. Why it matters
In an ELT pipeline (extract, load, then transform), raw data lands in the warehouse first and is transformed there with SQL. The transformation step is where most business logic lives: what counts as a sale, how a refund changes revenue, which customers are active. In many companies that logic starts as a stored procedure, a scheduled script on someone's laptop, or a query pasted into the warehouse console. It works until it has to change.
Four problems appear again and again with that approach:
- No review. Someone edits the procedure in the production database. Nobody else sees the change before it runs, and the old version is gone.
- No tests. Nothing checks that
order_idis still unique after the change. The first sign of a bug is a wrong number on a dashboard. - No lineage. Lineage is the map of which table is built from which. Without it, a renamed source column means searching the code by hand.
- One environment. The script names
analytics.ordersdirectly, so you cannot run it safely against a copy of the data. Testing a change means running it in production.
Software teams solved the same problems years ago with version control, pull requests, automated tests and separate environments. dbt (data build tool) applies those habits to SQL transformations. You keep each transformation as a .sql file in a Git repository, and dbt runs the files in the right order against the environment you choose.
02. A model is a SELECT; dbt writes the DDL
A dbt model is one .sql file that contains one SELECT statement. You do not write CREATE TABLE or INSERT. The model's materialisation setting tells dbt how to store the result: as a view, a table, or one of the forms you meet in lesson 3. dbt wraps your SELECT in the right DDL (data definition language, such as CREATE TABLE ... AS) and runs it.
The example below is small enough to type in two minutes. It uses DuckDB, an embedded analytical database that stores everything in one local file, so you need no server. It was tested with dbt Core 1.12.7, the dbt-duckdb adapter 1.11.1 and DuckDB 1.5.6 on Python 3.12. An adapter is the plug-in that teaches dbt one database's SQL dialect. Pin all three versions. Today pip install dbt installs dbt v2, a newer engine. This course uses the v1 line, which dbt Labs still supports; the v2 upgrade guide says the project language and the DAG work the same, once deprecated features are removed.
mkdir demo && cd demo
python3 -m venv .venv && source .venv/bin/activate
pip install "dbt-core==1.12.7" "dbt-duckdb==1.11.1" "duckdb==1.5.6"
mkdir models seedsA project needs two settings files. dbt_project.yml names the project and the connection profile it uses. profiles.yml holds the connection details for each target, which is one environment you can build into. Here both targets use the same DuckDB file but different schemas, dev and prod. Unless a flag or an environment variable points elsewhere, dbt v1 finds profiles.yml in the current folder before it tries ~/.dbt/, so keeping it next to the project is fine for a local exercise. In a real team it usually lives outside the repository, because it holds credentials.
name: demo
version: "1.0.0"
profile: demodemo:
target: dev
outputs:
dev:
type: duckdb
path: demo.duckdb
schema: dev
prod:
type: duckdb
path: demo.duckdb
schema: prodFor raw data, this example uses a seed: a small CSV file in seeds/ that dbt loads as a table. Seeds suit small, static lookup data such as country names. Real raw tables arrive through an ingestion tool and are declared as sources, which the lab does. The first model renames and converts columns. The second adds up shipped orders per customer and asks for a table.
id,cust,amount_cents,status
1,10,2500,shipped
2,11,1200,cancelled
3,10,4000,shipped
4,12,999,shippedselect
id as order_id,
cust as customer_id,
amount_cents / 100.0 as amount,
status
from {{ ref('raw_orders') }}{{ config(materialized='table') }}
select customer_id, sum(amount) as revenue
from {{ ref('stg_orders') }}
where status = 'shipped'
group by customer_iddbt build loads the seed and builds both models in dependency order. Then dbt show runs a model's query and prints the first rows. Your clock times and durations will differ from the excerpt below.
dbt build23:22:23 Running with dbt=1.12.7
23:22:24 Registered adapter: duckdb=1.11.1
23:22:29 Found 2 models, 1 seed, 511 macros
...
23:22:30 Done. PASS=3 WARN=0 ERROR=0 SKIP=0 NO-OP=0 REUSED=0 TOTAL=3dbt show --select customer_revenue --quiet| customer_id | revenue |
| ----------- | ------- |
| 10 | 65.00 |
| 12 | 9.99 |If you see 65,00 instead of 65.00, your system locale uses a decimal comma; run export LC_NUMERIC=en_US.UTF-8 to match the output above. dbt keeps the exact SQL it sent to the database under target/run/. The grep below hides the blank lines that template tags leave behind.
grep -v '^ *$' target/run/demo/models/customer_revenue.sql create table
"demo"."dev"."customer_revenue__dbt_tmp"
as (
select customer_id, sum(amount) as revenue
from "demo"."dev"."stg_orders"
where status = 'shipped'
group by customer_id
);Your query is inside a CREATE TABLE ... AS that dbt wrote. dbt builds the new table under a temporary name, customer_revenue__dbt_tmp, then renames it into place and drops the old copy. On DuckDB the swap is committed as one transaction, so a query during the build sees the old table or the new one, not a half-built one. Notice also that {{ ref('stg_orders') }} has become "demo"."dev"."stg_orders": database, schema and name. The next section explains where that name came from.
03. ref() and source(): names that follow the environment
The text inside {{ ... }} is Jinja, a template language. dbt renders it before the SQL reaches the database; the result is called the compiled SQL. Two Jinja functions matter most. ref('model_name') points at another model or seed in the project. source('source_name', 'table_name') points at a raw table that something outside dbt loads; you declare those tables in YAML, as the lab shows.
Each call does two jobs. First, dbt replaces it with the full relation name for the current target. dbt compile shows the result without running anything, and --quiet hides the log lines so only the SQL is printed. Compile the same model for both targets:
dbt compile --select customer_revenue --quiet
dbt compile --select customer_revenue --quiet --target prodselect customer_id, sum(amount) as revenue
from "demo"."dev"."stg_orders"
where status = 'shipped'
group by customer_id
select customer_id, sum(amount) as revenue
from "demo"."prod"."stg_orders"
where status = 'shipped'
group by customer_idThe model file did not change, but the dev build reads from dev and the prod build reads from prod. That is what makes separate environments possible: a developer builds into a personal schema, a CI job builds into a throwaway schema, and the scheduled job builds production, all from the same commit.
Second, dbt records every ref() and source() call it finds while it parses the project, that is, reads the files before running anything. Each call becomes an edge in a DAG (directed acyclic graph): a graph of nodes joined by one-way arrows that never loop back. dbt uses the DAG to run models in order and to answer questions about lineage. dbt ls lists the nodes a selector matches. A + before a name adds everything upstream (its ancestors); a + after a name adds everything downstream (its descendants).
dbt ls --select +customer_revenue --output name --quiet
echo "---"
dbt ls --select raw_orders+ --output name --quietcustomer_revenue
stg_orders
raw_orders
---
customer_revenue
stg_orders
raw_ordersIn a three-node chain both lists are the same, but the idea scales. In a project of 400 models, +fct_orders tells you exactly what a number depends on, and stg_payments+ tells you what a change to payments could break. Hard-code a table name instead of calling ref(), and that edge disappears from the graph; the lab shows the effect.
04. Sources, staging, intermediate and marts
A project with hundreds of models needs a convention for where each kind of logic goes. The widely used layout from the dbt Labs guide has four layers, and data flows through them in one direction:
- Sources are the raw tables, declared in YAML with
source(). dbt does not build them; it reads them, documents them and can test them. - Staging models have one model per source table, usually named
stg_<table>. They rename columns, cast types, convert units such as cents to pounds, and do light cleaning. They do not join or aggregate. Every other model reads raw data only through staging, so a renamed source column is fixed in one file. - Intermediate models, named
int_<description>, combine staging models into reusable building blocks: a join, a deduplication, a per-order total of payments. They are usually not exposed to business users. - Marts are the tables people and dashboards use, such as
fct_ordersfor events and measures anddim_customersfor descriptive attributes. These are the fact and dimension tables from dimensional modelling.
Folders mirror the layers (models/staging/, models/intermediate/, models/marts/), so dbt_project.yml can give each folder its own defaults. The layers are a convention, not a rule dbt enforces. A small project can skip intermediate models until a join is needed twice. What matters is that a reviewer can guess from a model's name what it may contain, and that raw tables are read in exactly one place.
Put together, a change to revenue logic becomes a pull request that touches one or two .sql files. A colleague reviews the diff, CI builds and tests the changed models in a scratch schema, and the DAG shows which marts are affected.
05. Check your understanding
06. Apply it
The practice project for this skill turns raw e-commerce tables into a dbt project with staging models, an incremental fact table, a customer snapshot and a documented mart, built by CI on every pull request. Before the lab, sketch its graph on paper:
- List the raw tables you expect (customers, orders, payments) and write one
stg_model name for each. - Decide which joins two marts would share, and name an
int_model for each. - Name the marts and draw the arrows. Each arrow will become a
ref()orsource()call.
Keep the sketch. In the lab you build the project and compare your arrows with the graph dbt reports.
07. Review prompt
Without looking back, explain in your own words:
- four problems of transformations kept as stored procedures or hand-run scripts;
- what dbt adds around a model's
SELECT, and why it builds tables under a temporary name; - the two jobs that a
ref()call does; - what belongs in staging, intermediate and mart models, and why raw tables are read in only one place.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.