dbt: The SQL-First Transformation Tool for Data Teams
Discover how dbt brings software engineering practices—version control, testing, documentation—to SQL-based data transformations.
dbt can fit teams that already transform warehouse data in SQL and want models, dependencies, and configured checks in one project. Its tests only check the assertions a team writes; freshness, ownership, and response still need separate monitoring. The examples here use familiar dbt project conventions, while current installation and product names vary by version.
dbt: The SQL-First Transformation Tool Transforming Data Teams
dbt began as an open-source tool for writing SQL transformations against a data warehouse. It can suit a team that already works in SQL and wants model dependencies, version control, and configured checks in one project. It may be a poor fit when transformations are mostly non-SQL, the warehouse is not the execution engine, or a simpler scheduled SQL job already meets the need.
As of November 2026, dbt’s docs call the current major generation dbt v2; dbt OSS is the Apache 2.0 distribution, dbt v1 refers to the Python-based generation, and dbt platform is the hosted service (formerly dbt Cloud). Product and command details change; check the official version guide and setup guide before installing. The SQL and YAML snippets below use dbt’s familiar project conventions; command examples use the dbt v2 CLI documented in the command reference.
The Core Philosophy: SQL as Code
dbt’s insight was that analysts already know SQL but rarely treat it as software. SQL queries live in Slack messages, shared Google Docs, or BI tool configurations. Nobody reviews them, nobody versions them, nobody tests whether they still work when upstream data changes.
dbt wraps SQL in a project structure that enables collaboration. Each transformation is a discrete model file. Models reference each other through a directed acyclic graph (DAG). You write SQL SELECT statements, and dbt materializes them as tables or views in your warehouse.
-- models/marts/fact_orders.sql
{{ config(materialized='table') }}
SELECT
o.order_id,
o.order_date,
o.customer_id,
o.store_id,
c.customer_name,
c.customer_segment,
c.region,
p.product_name,
p.category,
p.brand,
s.store_name,
s.store_region,
s.store_country,
oi.quantity,
oi.unit_price,
oi.quantity * oi.unit_price AS line_revenue,
oi.unit_cost,
oi.quantity * (oi.unit_price - oi.unit_cost) AS line_profit
FROM {{ source('raw_orders', 'orders') }} o
JOIN {{ source('raw_orders', 'order_items') }} oi ON o.order_id = oi.order_id
JOIN {{ ref('dim_customer') }} c ON o.customer_id = c.customer_id
JOIN {{ ref('dim_product') }} p ON oi.product_id = p.product_id
JOIN {{ ref('dim_store') }} s ON o.store_id = s.store_id
WHERE o.order_status = 'completed'
The {{ ref('dim_customer') }} syntax creates lineage. dbt resolves this to the correct schema.table in your warehouse, and it builds the dependency DAG automatically. When you run dbt run, dbt executes models in topological order, ensuring that dim_customer exists before fact_orders depends on it.
Materializations: How Models Are Stored
dbt supports four materialization strategies that control when and how models are created in your warehouse.
Table materialization creates a physical table. Querying a table is fast but the table needs to be refreshed when source data changes. Use for large datasets that are queried frequently.
View materialization creates a SQL view. No data is stored beyond the view definition. Queries always see current source data but are slower on complex transformations. Use for transformations that are cheap and need always-fresh results.
Incremental materialization builds a table and then processes a selected subset of rows on later runs. It can reduce repeated work on large historical datasets, but it is not a streaming engine. The model’s filter, unique key, late-arriving data policy, and periodic backfill determine whether the result stays correct.
Ephemeral materialization creates a Common Table Expression (CTE) that other models inline. The model does not exist as a warehouse object. Use for intermediate transformations that are only consumed by other models.
-- models/marts/dim_orders incremental.sql
{{ config(
materialized='incremental',
unique_key='order_id',
partition_by={'field': 'order_date', 'data_type': 'date'}
) }}
SELECT
order_id,
order_date,
customer_id,
store_id,
order_status,
total_amount,
row_number() OVER (PARTITION BY order_id ORDER BY _loaded_at DESC) AS rn
FROM {{ source('raw_orders', 'orders') }}
{% if is_incremental() %}
WHERE _loaded_at > (SELECT MAX(order_date) FROM {{ this }})
{% endif %}
The is_incremental() macro generates a filter that only loads new rows on subsequent runs. This incremental pattern is central to dbt workflows for large datasets.
Testing: Asserting Data Quality
dbt’s schema tests let you define expectations about your data and validate them automatically. Tests live in schema.yml files alongside your models.
# models/marts/schema.yml
version: 2
models:
- name: fact_orders
description: Order fact table with line-level revenue
columns:
- name: order_id
description: Primary key
tests:
- unique
- not_null
- name: customer_id
description: Foreign key to customer dimension
tests:
- not_null
- relationships:
to: ref('dim_customer')
field: customer_id
- name: order_date
tests:
- not_null
- name: line_revenue
description: Revenue per line item
tests:
- not_null
- dbt_utils.accepted_range:
min: 0
max: 1000000
Run dbt build --select fact_orders to build the selected model and run its configured tests. A passing result means those assertions passed on that run; it does not establish that untested fields are correct or that upstream data is fresh. Assign an owner to each important check and alert on source freshness separately where late data matters.
For example, if order_id has unique and not_null tests, the expected result is a passing model build when each value is present and occurs once. A row with a duplicate order_id should make the uniqueness test fail and return that test’s failing rows. Those checks say nothing about whether the latest source batch arrived on time.
Custom tests let you define arbitrary SQL that returns zero rows if the test passes. You can test business logic, not just schema constraints.
-- tests/checks/no_orders_with_negative_revenue.sql
SELECT order_id
FROM {{ ref('fact_orders') }}
WHERE line_revenue < 0
-- If any rows return, the test fails
Documentation: Making Knowledge Explicit
dbt generates documentation from your project and warehouse metadata. Column descriptions in schema.yml become a data dictionary. Lineage graphs show how models connect. You can even embed diagrams showing the full DAG.
/*(
name: fact_orders
description: One row per order line item. Completed orders only.
dimensions:
- customer_name: Name from dimension table
- category: Product category
- order_date: Calendar date of order
measures:
- line_revenue: Quantity times unit price
- line_profit: Revenue minus cost
)*/
SELECT ...
The documentation site is a static HTML site served from your CI/CD pipeline. When a new analyst joins the team, they can explore the warehouse through the documentation rather than reverse-engineering SQL files.
The Analytics Engineering Workflow
dbt coined the term “analytics engineering” to describe the discipline between data engineering (moving data from sources to warehouse) and business intelligence (building dashboards and reports). Analytics engineers own the transformation layer—the SQL models that structure raw data into business concepts.
The workflow depends on the installed generation and adapter. With dbt v2, the current CLI supports commands such as dbt compile, dbt build, and dbt docs generate; check the official command reference for your version. A typical change is:
Pull the latest changes from version control, install project dependencies, compile the project, then build and test the selected models. Submit the change for review and run the same checks in CI before deployment. A dbt build result covers the configured models and tests in its selection; source freshness and operational alerts remain separate.
Analytics Engineering Workflow
flowchart LR
subgraph Dev[Development]
CODE[Write SQL Model]
COMPILE[dbt compile]
TEST_DEV[dbt test]
end
subgraph PR[Pull Request]
CI[CI Pipeline]
DAG[dbt deps + compile]
TEST_CI[dbt test]
end
subgraph Prod[Production]
RUN[dbt run]
TEST_PROD[dbt test]
DOCS[dbt docs generate]
end
CODE --> COMPILE --> TEST_DEV
TEST_DEV --> PR
PR --> CI --> TEST_CI
TEST_CI -->|pass| RUN
RUN --> TEST_PROD
TEST_PROD --> DOCS
CI -.->|fail| PR
TEST_PROD -.->|fail| RUN
Every model change goes through local compile → local test → PR CI → production run. The DAG is automatically resolved by dbt’s dependency engine.
# Typical dbt workflow
git checkout -b feature/add-customer-segment
# Edit models
dbt compile # Validate SQL syntax
dbt run --select +dim_customer # Run dim_customer and all downstream models
dbt test --select dim_customer # Test only this model
git commit -m "Add customer segment to dim_customer"
git push origin feature/add-customer-segment
# Open PR, get review, merge
dbt build # Full build in production
Packages extend dbt with reusable macros and models. The dbt-utils package provides common patterns (surrogate keys, date handling, pivot queries). Other packages port established frameworks like Marketing Mix Modeling or common analytics patterns.
dbt platform and self-hosted dbt
The dbt platform is hosted and provides managed project environments and collaboration features. Check current plans and features in the official setup documentation; names and availability have changed over time.
Self-hosted dbt v2 or dbt v1 runs in infrastructure your team operates. The team chooses how to schedule jobs, provide credentials, store artifacts, and connect deployment checks. The choice depends on adapter support, licensing needs, existing orchestration, and who will operate the environment.
There is no size-based rule. Compare the hosted service with self-hosting against your adapter support, security requirements, operating capacity, and existing workflow before choosing.
dbt Production Failure Scenarios
Test failures blocking critical pipelines
A data quality test on fct_orders starts failing intermittently. The CI pipeline blocks all model deployments. Analysts keep submitting PRs that fail CI. The team disables the test to get work done. Downstream dashboards start showing null customer IDs.
dbt tests run after model materialization. When a test fails, the dbt run exits with a non-zero code, which most CI systems interpret as a failure. This is correct behavior when the test failure indicates real data problems—but it becomes a bottleneck when tests are flaky or when the underlying data issue takes days to fix while business needs force deployments.
The danger escalates when teams disable failing tests to unblock work. A disabled test does not alert on subsequent runs. The data quality issue persists and propagates silently. Dashboards built on faulty data produce wrong numbers. By the time someone notices, the incorrect data has informed business decisions.
The root cause of the intermittent failure matters. Some tests fail because of timing—source data arrives late and the test runs before the expected rows are present. Others fail because of data quality regressions introduced gradually. A test that fails 10% of the time due to timing issues looks like a flaky test but actually signals an upstream pipeline with inconsistent delivery SLAs.
Mitigation: Treat test failures as incidents, not annoyances. Add alerting on test failure rate to PagerDuty or Slack. If a test must be disabled temporarily, open a ticket to re-enable it within 24 hours and assign to someone.
Silent model failure from exception handling
A model fails mid-execution. dbt reports the failure in the logs but the CI pipeline only checks exit code. The deploy job retries the failed model once, succeeds on retry, and reports success. The team never knows the first attempt failed.
dbt run returns exit code 0 if all models eventually succeed, even if some models failed and were retried. The CI pipeline sees green because it only checks the final exit code. What it does not capture is that the retry mechanism worked around an underlying problem—transient infrastructure issue, temporary network glitch, or a model that is right at the edge of timing out.
A single retry succeeding masks a real problem. If a model consistently fails the first attempt and only passes on retry, that is a signal about resource contention, cold start latency, or a model that is too complex for its allocated runtime. Ignoring it means the problem compounds as data volume grows, until the retry also fails and the pipeline breaks at the worst possible moment.
The pattern is especially dangerous for incremental models. If an incremental model fails on first attempt, retries, and succeeds, the model materialization may be incomplete. The model might have processed only a subset of the expected rows, or the unique_key logic might have skipped records due to the failure occurring mid-execution. Downstream models that depend on this incremental runs never see the missing rows.
Mitigation: Set on_failure: halt in the CI/CD configuration to halt on any model failure. Track model failure rate over time with dbt Cloud metrics or a custom dashboard querying the run artifacts table.
Upstream schema change breaking downstream models
The source raw_orders table adds a column. The new column has a different type than expected. The dim_orders model silently produces wrong results because no schema test catches the type mismatch. Dashboards show incorrect totals until someone notices manually.
Mitigation: Add schema tests (not_null, unique, accepted_range) on all source columns. Add dbt source freshness checks to detect upstream data delays. In CI, run dbt source freshness and fail if sources are stale.
Summary
dbt changed how data teams work. It made SQL transformations testable, version-controllable, and collaborative. It created the analytics engineering discipline. It spawned an ecosystem of packages and integrations that make building data pipelines faster.
The core lesson of dbt is that analytical code is still code. It needs review, testing, documentation, and version control. The fact that it is SQL does not make it less important or less prone to bugs.
dbt Observability
Track these metrics to keep the dbt project healthy:
-- dbt run artifacts in the artifacts table (dbt Cloud or dbt'inv metadata)
-- Monitor model execution times
SELECT
model_name,
AVG(execution_time_seconds) as avg_runtime,
MAX(execution_time_seconds) as p99_runtime,
COUNT(*) as run_count,
SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as error_count
FROM dbt_run_results
WHERE run_started_at > NOW() - INTERVAL '7 days'
GROUP BY model_name
HAVING error_count > 0 OR avg_runtime > 1000
ORDER BY avg_runtime DESC;
-- Track test result history
SELECT
test_name,
COUNT(*) as total_runs,
SUM(CASE WHEN result = 'pass' THEN 1 ELSE 0 END) as pass_count,
SUM(CASE WHEN result = 'fail' THEN 1 ELSE 0 END) as fail_count
FROM dbt_test_results
WHERE run_at > NOW() - INTERVAL '30 days'
GROUP BY test_name
HAVING fail_count > 0;
Log per run: model name, execution time, rows affected, status. Alert on: any model error, any test failure in production, runtime > 2x the 7-day average.
dbt Anti-Patterns
Monolithic models that do everything. A single 500-line SQL model joining 20 tables in nested CTEs. Nobody understands it, nobody tests it, it takes 3 hours to run. Break it into discrete models with clear intermediate outputs.
Skipping tests on “simple” models. Every model needs at least a not_null test on the primary key. The broken model that takes down dashboards is always the one nobody thought needed testing.
Materializing views for large datasets. Views recompute their SQL on every query. A view reading 500GB makes BI tools crawl. Use materialized='table' for large datasets.
No naming conventions. stg_orders, fact_orders, and base_orders_v2 all mean different things to different people. Establish conventions (staging, intermediate, fact/dim) and enforce them in code review.
Quick Recap
- dbt treats SQL as code: version control, test, document, and deploy transformations with the same rigor as application code.
{{ ref() }}creates lineage DAGs that dbt resolves automatically ondbt run.- Use
incrementalmaterialization for streaming data or large historical datasets. - Schema tests catch bad data before it reaches dashboards. Run
dbt testin CI before every deployment. - dbt Cloud for teams wanting managed infrastructure; dbt Core for teams with existing orchestration.
Conclusion
dbt is one option for teams that want to manage SQL transformations as a project with dependencies and explicit checks. Start with one model, name the assertions that matter, and decide who responds when a check fails or source data is late. Check the current version and adapter support before adopting it.
To understand how Spark fits into the processing ecosystem, see Apache Spark. For query engines that federate across sources, read about Presto and Trino.
Category
Related Posts
Data Warehouse Architecture: Layers, Flow, and Ownership
Plan warehouse data flow, layer boundaries, ownership, and operational checks. Compare ETL and ELT and see how physical design varies by provider.
DuckDB: The SQLite for Analytical Workloads
Explore DuckDB, the in-process analytical database that runs anywhere, handles columnar storage efficiently, and brings analytics to where your data lives.
ELT Pattern: Transforming Data in the Data Warehouse
ELT flips ETL by loading raw data first, then transforming in the warehouse. Learn how modern cloud platforms enable ELT at scale.