Chapter 5 of 12
Course Progress0 of 12 completed (0%)

Data Engineering · Chapter 5 · ~15 min · Intermediate

Transformation with dbt & SQL Models

Master analytics engineering with dbt: declarative SQL models, ref() DAG dependencies, ephemeral/view/table/incremental materializations, automated schema testing, and documentation.

  • Structure enterprise data models into staging, intermediate, and marts using dbt
  • Master the ref() macro to build automated dependency DAGs without manual scheduling
  • Configure table, view, and incremental materializations with unique_key and merge strategies
  • Implement automated testing: unique, not_null, accepted_values, and custom singular tests

Transformation with dbt & SQL Models: learn it visually

Master analytics engineering with dbt: declarative SQL models, ref() DAG dependencies, ephemeral/view/table/incremental materializations, automated schema testing, and documentation.

Transformation with dbt & SQL ModelsMaster analytics engineering with dbt: declarative SQL models, ref() DAG dependencies, ephemeral/view/table/incremental materializations, automated schema testing, and documentation.UNDERSTANDTransformation dbtFOLLOW THE FLOWSQL ModelsAPPLY ITanalyticsengineering dbtTransformation with dbt & SQL ModelsMaster analytics engineering with dbt: declarative SQL models, ref() DAG dependencies, ephemeral/view/table/incremental materializations, automated schema testing, and documentation.UNDERSTANDTransformation dbtFOLLOW THE FLOWSQL ModelsAPPLY ITanalyticsengineering dbt

1Everyday Intuition: Bringing Software Engineering Rigor to SQL

Before tools like dbt (data build tool), analytics teams operated in an era of "spaghetti SQL". Companies ran hundreds of unversioned stored procedures inside production databases, scheduled by arbitrary cron jobs or manual analyst scripts.

dbt brought foundational software engineering best practices to data teams:

Best Practice 1

Modularity & DRY

Don't Repeat Yourself (DRY). Business definitions like "Active Paying Customer" are declared once in an intermediate model and referenced everywhere else.

Best Practice 2

Git Version Control

Every SQL transformation lives in a git repository with pull request code reviews, continuous integration (CI) tests, and branch deployments.

Best Practice 3

Automated Lineage

By using the {{ ref() }} macro, dbt automatically resolves parent-child relationships and compiles a topological Directed Acyclic Graph (DAG).

Concept Check

What does the {{ ref('model_name') }} Jinja macro accomplish in a dbt project?

2Under the Hood: Materializations & Incremental Processing

In dbt, a model is simply a SELECT statement saved in a .sql file. dbt wraps this SELECT inside the DDL (Data Definition Language) corresponding to its configured materialization:

1. view

Creates a standard SQL CREATE VIEW. Consumes zero storage and always executes fresh against underlying tables. Best for lightweight staging models.

2. table

Rebuilds the physical table from scratch (CREATE TABLE AS SELECT). Very fast to query for BI dashboards, but slow and expensive to rebuild if rows exceed 100 million.

3. incremental

Appends or merges only new or updated rows into an existing table. Requires a unique_key and an is_incremental() Jinja block to filter on watermarks (e.g. updated_at).

4. ephemeral

Never written to the database; interpolated as a Common Table Expression (CTE) into downstream models that reference it.

Wrong idea: Hardcode physical database and schema paths in SQL

dev_user running query → Overwrites `production_db.raw_data.orders`!No environment isolation · Manual dependency tracking

Writing queries like 'FROM production_db.raw_data.orders' in 60 separate scripts. When a developer runs the pipeline in local dev, they accidentally overwrite production tables.

Real system: Use {{ ref('stg_orders') }} for dynamic environment resolution

{{ ref("stg_orders") }} → dev schema in Dev, prod schema in ProdAutomated lineage graph · 100% environment isolation

dbt dynamically swaps schemas between dev, staging, and prod targets while simultaneously building an execution DAG that calculates parallel run order.

Concept Check

Why must incremental dbt models specify a unique_key configuration?

3Hands-On: Test dbt Build & Circuit Breaker Gates

Trigger a dbt build run below. Observe how dbt executes models in topological order, and test what happens when an upstream staging model violates a not_null constraint:

dbt Core Engine v1.8

dbt Lineage DAG & Test Gate Simulator

Trace how ref() dependencies order execution and how schema tests halt downstream corruptions.

Step 1
view
source('stripe', 'charges')
Ready
Step 2
view
stg_stripe__payments
Ready
Step 3
table
int_customer_spend
Ready
Step 4
incremental
fct_monthly_mrr
Ready
Concept Check

When should a data team choose materialized='view' over materialized='table' in dbt?

4Bug Hunt: Fix an Incremental dbt Model

An analytics engineer created an incremental model to track daily orders. However, it hardcodes production database names, omits the unique key (causing duplicate orders on every batch run), and misses the watermark condition. Fix the model and run verification:

dbt SQL Modeling · Lineage & Incremental Logic
SQL

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?
  • Replace the hardcoded database path with {{ ref('stg_orders') }}.
  • Add unique_key = 'order_id' to the {{ config(...) }} block.
  • Add {{ this }} watermark check inside a {% if is_incremental() %} block.

5Recap

  • dbt (data build tool) applies modern software engineering principles (git, testing, modularity, CI/CD) to SQL data modeling.
  • The {{ ref() }} macro dynamically points to dev or prod schemas and automatically compiles the execution DAG.
  • Incremental Materialization uses watermarks (is_incremental()) and unique_key to merge only modified records, slashing warehouse compute spend.
  • Schema Testing (unique, not_null, accepted_values, foreign keys) acts as an automated circuit breaker, halting pipelines before corrupt data reaches BI dashboards.

Ready for Chapter 6? Mark this chapter as complete to proceed:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us