The dbt Field Guide
A working-knowledge reference on dbt (data build tool): what it is, how it's built, how the major cloud platforms implement it, how to run the whole thing for free, and the questions you're actually likely to be asked.
What dbt Is
The short version, and why it exists.
dbt (data build tool) is the "T" in ELT. It is a transformation framework that lets analytics engineers write data transformations as SQL SELECT statements (or Python models, on supported adapters) and turns them into a managed, tested, documented, version-controlled pipeline that runs inside your data warehouse. dbt does not extract data from source systems and does not load it into the warehouse — that's the job of tools like Fivetran, Airbyte, or Meltano. dbt's entire job starts once raw data already lives in the warehouse, and its job is to turn that raw data into clean, trusted, analysis-ready tables and views.
Before dbt (which shipped its first public release from a small consultancy called Fishtown Analytics in 2016, later renamed dbt Labs), the "T" step of a data pipeline was usually a tangle of stored procedures, cron-scheduled Python scripts, or a proprietary ETL tool's drag-and-drop canvas. None of that was testable, reviewable, or documented by default. dbt's founding insight, borrowed deliberately from software engineering, was that analytics code deserves the same discipline as application code: version control, code review, automated testing, CI/CD, modularity, and documentation as a first-class citizen rather than an afterthought. That single idea — "treat analytics like software" — is the correct one-sentence answer if an interviewer asks you to define dbt in a sentence.
What dbt does
Compiles SQL + Jinja templates into warehouse-native SQL, executes it in dependency order, and materializes the results as tables, views, or incremental tables — while running data tests and generating documentation and lineage along the way.
What dbt doesn't do
It doesn't extract data from source systems, doesn't load data into the warehouse, isn't a scheduler by itself (dbt Core), isn't a BI tool, and isn't a database. It orchestrates within a run, not across systems.
Where it sits in the modern data stack
dbt is the transformation layer of the "modern data stack": extract/load tools move raw data into a cloud warehouse or lakehouse, dbt transforms it into modeled layers, and BI or reverse-ETL tools consume the output. It assumes an ELT pattern (Extract, Load, then Transform) rather than the older ETL pattern, because it depends on the raw data already sitting in a warehouse powerful enough to do heavy transformation work in-database.
| Stage | Typical tools | dbt's role |
|---|---|---|
| Extract & Load | Fivetran, Airbyte, Meltano, Stitch, custom scripts | None — dbt starts after data lands |
| Transform | dbt Core / dbt Fusion / dbt Platform | Everything: modeling, testing, docs, lineage |
| Orchestrate | Airflow, Dagster, Prefect, dbt Platform jobs | dbt is invoked as a task; it doesn't schedule itself outside dbt Platform |
| Serve / Consume | Looker, Tableau, Power BI, Hex, reverse-ETL | Reads dbt's output tables, or queries the Semantic Layer |
If you only remember one sentence: "dbt turns SQL SELECT statements into a version-controlled, tested, documented pipeline of views and tables — it's the transformation layer of ELT, not the extract/load/orchestration layer." That single distinction (T, not E-L) is the most commonly probed misconception.
Core Concepts
The vocabulary you need before anything else makes sense.
Models, ref() and source()
A model is a single .sql file containing one SELECT statement. That's it — no CREATE TABLE, no DDL. dbt wraps your query in whatever DDL/DML is needed based on how you've configured the model to materialize. Models live in the models/ directory and each one becomes a view or table in the warehouse.
Two Jinja functions hold the whole dependency graph together:
{{ source('raw_stripe', 'payments') }}— references a raw table declared in asources:YAML block, so dbt knows where the DAG starts and can test/document freshness on raw tables it didn't create.{{ ref('stg_payments') }}— references another dbt model by name, not by hard-coded schema/table. This is the single most important idiom in dbt: it's how dbt builds the DAG, resolves models into the right environment (dev schema vs. prod schema) automatically, and lets you rename a table without breaking sixty downstream queries.
-- pulls the DAG edge from source and casts types; no CTAS needed
with source as (
select * from {{ source('stripe', 'payments') }}
),
renamed as (
select
id as payment_id,
orderid as order_id,
paymentmethod as payment_method,
cast(amount as numeric) / 100 as amount,
cast(created as timestamp) as created_at
from source
)
select * from renamed
Everything downstream of this model references it with {{ ref('stg_payments') }}, never a hard-coded table path. That's what makes dbt's dependency graph automatic instead of manually maintained.
Materializations
A materialization tells dbt what SQL to wrap your SELECT in. It's set with {{ config(materialized='table') }} at the top of a model, in dbt_project.yml, or via folder-level defaults.
| Materialization | What it builds | When to use it |
|---|---|---|
| view | A database view (default) | Lightweight staging models; cheap to build, always fresh, slower to query |
| table | A full table, rebuilt every run | Marts that get queried heavily by BI tools; trade build time for query speed |
| incremental | A table that's appended/merged/deleted into on each run | Large, append-heavy fact tables where a full rebuild is too slow or costly |
| ephemeral | Nothing in the warehouse — inlined as a CTE into models that reference it | Lightweight reusable logic you don't want cluttering the warehouse schema |
| materialized_view | A native warehouse materialized view (Snowflake, Databricks, Postgres, Redshift) | Near-real-time incremental refresh handled by the warehouse engine itself |
| snapshot | A slowly-changing-dimension (SCD Type 2) table tracked over time | Capturing history of mutable source records (e.g. an order's status changing) |
Ephemeral models are not built as objects at all — they're compiled inline as CTEs wherever referenced. That means you can't query them directly in the warehouse, and overusing them produces enormous, hard-to-debug compiled SQL. Reach for them for small reusable snippets, not entire staging layers.
Jinja templating and macros
dbt compiles every model through Jinja, the Python templating engine, before sending it to the warehouse. This is what enables ref()/source(), control flow ({% if %}, {% for %}), and macros — reusable snippets of SQL logic defined once and called everywhere, dbt's answer to functions.
{% macro cents_to_dollars(column_name, decimal_places=2) %}
(round({{ column_name }} / 100.0, {{ decimal_places }}))
{% endmacro %}
-- used in a model as: {{ cents_to_dollars('amount') }}
dbt also ships packages — installable libraries of macros and models, distributed through packages.yml and the dbt Hub/package index. dbt_utils (date spines, surrogate keys, pivot helpers) and dbt_expectations (a richer testing vocabulary inspired by Great Expectations) are close to universal in real projects, and codegen/audit-helper packages are common enough to be worth naming in an interview.
Tests and data contracts
Every model can carry tests — assertions about the data that dbt compiles to SQL and runs as part of dbt test or dbt build. There are two flavors:
- Generic (schema) tests — reusable, parameterized tests declared in YAML: the four built-ins are
unique,not_null,accepted_values, andrelationships(referential integrity). Packages likedbt_utilsanddbt_expectationsadd dozens more (row count comparisons, freshness, distribution checks). - Singular tests — a one-off
.sqlfile intests/that returns failing rows; anything a generic test can't express. - Unit tests (dbt Core 1.8+) — mock input rows and assert on expected output rows for a model's SQL logic itself, independent of what's actually in the warehouse. This is the closest dbt gets to a traditional software unit test, and it's a newer feature interviewers increasingly probe for.
models:
- name: stg_payments
columns:
- name: payment_id
tests: [unique, not_null]
- name: payment_method
tests:
- accepted_values:
values: ['credit_card', 'paypal', 'bank_transfer']
- name: order_id
tests:
- relationships:
to: ref('stg_orders')
field: order_id
Sitting alongside tests are data contracts: a model can declare an enforced column-level schema (name, type, nullability) so that a breaking change fails the build immediately rather than silently propagating downstream — the analytics-engineering equivalent of an API contract between producer and consumer teams.
Architecture & Components
What actually happens between typing dbt run and rows landing in the warehouse.
Project anatomy
A dbt project is a directory of YAML and SQL files, anchored by dbt_project.yml. Nothing about it is a running service — dbt is a command-line program (or, for dbt Platform, a hosted wrapper around the same engine) that reads this directory, compiles it, and pushes SQL to your warehouse over a database connection defined in profiles.yml (dbt Core) or the platform's connection settings (dbt Platform).
jaffle_shop/
├── dbt_project.yml # project config: name, materializations, paths
├── packages.yml # third-party package dependencies
├── models/
│ ├── staging/ # 1:1 with source tables; light cleaning, renaming, casting
│ │ ├── stripe/
│ │ │ ├── _stripe__sources.yml
│ │ │ ├── _stripe__models.yml
│ │ │ └── stg_stripe__payments.sql
│ ├── intermediate/ # reusable joins/logic, not exposed to BI tools
│ └── marts/ # wide, business-defined, consumer-facing tables
│ ├── finance/
│ └── marketing/
├── snapshots/ # SCD Type 2 history tracking
├── seeds/ # small static CSVs loaded as tables (country codes, etc.)
├── macros/ # reusable Jinja/SQL functions
├── tests/ # singular tests
└── analyses/ # ad hoc compiled SQL, not materialized
This staging → intermediate → marts layering is not enforced by dbt itself, but it is the near-universal convention (originating from dbt Labs' own style guide) and interviewers treat familiarity with it as table stakes. Staging models do the minimum: rename, cast, one-to-one with a source. Intermediate models do the messy joining/aggregating work, deliberately hidden from BI tools. Marts are the wide, denormalized, business-friendly tables analysts and dashboards actually query.
The DAG and the run lifecycle
Every ref() and source() call becomes an edge in a directed acyclic graph. When you run dbt run, dbt doesn't execute your files top to bottom — it topologically sorts the whole DAG and executes nodes in parallel up to the configured thread count, respecting dependencies, so a mart never runs before the staging model it depends on.
The output of the parse step, manifest.json, is the single most important build artifact in dbt: a full JSON representation of every model, test, macro, source, and the edges between them. It's what powers documentation, lineage graphs, and — critically — state comparison (--defer, state:modified) which lets CI runs build and test only the models that actually changed relative to a previous run, instead of the whole project.
| Artifact | Contains | Used for |
|---|---|---|
| manifest.json | Full project graph: models, tests, macros, sources, columns, config | Docs, lineage, state-based selection, dbt Explorer/Catalog |
| run_results.json | Per-node execution status, timing, rows affected, test pass/fail | CI reporting, observability dashboards, retry logic |
| catalog.json | Actual warehouse metadata (column types, table stats) via introspection | Populating the generated docs site with real schema info |
| sources.json | Freshness-check results for declared sources | dbt source freshness reporting/alerting |
Adapters and the Fusion engine
dbt itself contains no warehouse-specific SQL generation logic — that lives in adapter plugins (dbt-snowflake, dbt-bigquery, dbt-databricks, dbt-postgres, dbt-redshift, dbt-duckdb, and dozens more maintained by vendors or the community). An adapter translates dbt's warehouse-agnostic macros (like the materialization logic) into the specific SQL dialect and connection behavior of that platform. This plugin architecture is why the same dbt project can, with adapter and profile changes, target very different databases.
As of 2026, dbt Labs has been rolling out dbt Fusion, a new execution engine written in Rust that sits underneath the same dbt language and project structure. Unlike the original Python-based dbt Core engine — which compiles Jinja and hands finished SQL to the warehouse without understanding it — Fusion has native SQL comprehension across dialects, so it can catch invalid SQL, resolve column-level lineage, and power a real autocomplete/hover developer experience (via a VS Code extension) before anything reaches the warehouse. Fusion is built on an Apache-2.0-licensed open core (referred to as dbt Core 2.0) and ships free; dbt Labs' commercial layer, dbt Platform (the current name for what used to be marketed simply as dbt Cloud), adds hosted orchestration, environments, access control, the Semantic Layer, and a catalog/lineage UI on top of it.
Expect naming confusion here even among practitioners: dbt Core = the open-source CLI/engine; dbt Fusion = the newer Rust engine that is now the default install and understands SQL natively; dbt Platform = the commercial hosted product (renamed from "dbt Cloud"). You can run Fusion entirely locally and for free — the paid product is the hosted orchestration and collaboration layer around it, not the engine itself.
Advanced Features
Beyond the basics — the topics that separate junior from senior answers.
Incremental models and microbatch
An incremental model only processes new or changed rows on subsequent runs rather than rebuilding the full table, which matters enormously once a fact table reaches billions of rows. The model file itself uses an {% if is_incremental() %} block to filter to new data on incremental runs, while a full --full-refresh still rebuilds everything.
{{ config(materialized='incremental', unique_key='event_id', incremental_strategy='merge') }}
select * from {{ ref('stg_events') }}
{% if is_incremental() %}
where event_at > (select max(event_at) from {{ this }})
{% endif %}
The incremental_strategy config controls how new rows are merged in, and differs by adapter capability: append (simplest, no dedup), merge (upsert on a unique key — needs `MERGE` support), delete+insert, and insert_overwrite (partition replacement, common on BigQuery/Spark). Newer still is the microbatch strategy, purpose-built for very large, naturally time-partitioned datasets: you declare an event_time column and a batch_size (hour/day/month), and dbt automatically splits the incremental load into independent per-batch queries, retries failed batches individually, and backfills historical ranges — without you hand-writing the filtering logic.
Snapshots and exposures
Snapshots implement slowly-changing-dimension (Type 2) tracking: point them at a mutable source table and a strategy (timestamp or check columns), and dbt appends new rows with validity windows (dbt_valid_from/dbt_valid_to) every time it detects a change, building a full history of a row's state over time without you writing SCD logic by hand.
Exposures are a documentation/lineage feature: a YAML declaration that a dashboard, ML pipeline, or application depends on specific dbt models, extending the DAG's visibility one hop past the warehouse so that "what breaks if I change this column" answers itself in the lineage graph.
The dbt Semantic Layer & MetricFlow
The Semantic Layer lets you define metrics once — in code, on top of your existing models — with governed logic for aggregation, dimensions, and time granularity, then query that single definition consistently from Looker, Tableau, Hex, Google Sheets, or a plain SQL/GraphQL/JDBC interface, instead of every BI tool and analyst re-deriving "revenue" slightly differently. Underneath, this is powered by MetricFlow, which compiles a metric definition and a requested set of dimensions into optimized SQL at query time. You define semantic models (entities, dimensions, measures mapped onto existing dbt models) and metrics (simple, ratio, cumulative, derived) in YAML, and the Semantic Layer becomes the governed access point BI tools query rather than the physical warehouse tables directly.
dbt Mesh and multi-project architecture
As dbt adoption scales past a single team, one monolithic project becomes a bottleneck — every team waits on every other team's CI and shares one namespace. dbt Mesh is dbt Labs' answer: it lets you split a warehouse's transformation logic into multiple independently-versioned dbt projects that can safely reference each other's models via cross-project ref(), governed by explicit groups (ownership boundaries within a project) and model access modifiers (private, protected, public) plus versioned model contracts, so a downstream team can depend on a stable, versioned interface instead of an internal implementation detail. This is the analytics-engineering analogue of microservices and domain-driven design, and it's a strong signal of senior-level fluency in an interview.
Hooks, custom schemas, and environments
dbt supports pre-hook/post-hook and on-run-start/on-run-end config for arbitrary SQL that needs to run around a model or a whole invocation (grants, audit logging, vacuuming). Custom schema macros let you control how dev/target schemas are named so each developer gets an isolated sandbox schema without custom infrastructure. And every dbt invocation runs against a target defined in profiles.yml or a dbt Platform environment — typically at least dev and prod, often ci and staging too — which is how the same codebase safely builds into different schemas/databases depending on who's running it and why.
Vendor & Platform Landscape
How dbt actually shows up across the major cloud and warehouse ecosystems.
dbt Platform vs. dbt Core vs. Fusion
dbt Labs sells one product family across a spectrum of self-hosted to fully managed:
| dbt Core / Fusion (self-hosted) | dbt Platform (formerly dbt Cloud) | |
|---|---|---|
| License / cost | Free, open source (Apache 2.0) | Commercial SaaS — free developer tier, paid team/enterprise tiers |
| Where it runs | Your laptop, a container, your own orchestrator | dbt Labs' managed infrastructure |
| Scheduling/orchestration | None built in — bring your own (cron, Airflow, Dagster…) | Native job scheduler, retry logic, run history UI |
| Development experience | CLI + your own editor/IDE (VS Code extension for Fusion) | Hosted browser IDE, plus CLI/IDE integration |
| Docs & lineage | Self-hosted dbt docs generate static site | Hosted dbt Explorer / Catalog with column-level lineage, auto-updated |
| Governance | DIY: git branch protection, manual review | Role-based access control, environments, model access/contracts UI, dbt Mesh support |
| Semantic Layer | MetricFlow runs locally for development | Hosted Semantic Layer with BI-tool integrations and a query API |
| CI | Wire it up yourself in GitHub Actions/GitLab CI | Built-in "slim CI" using state comparison against prod |
In practice, most companies land somewhere in the middle: dbt Core/Fusion for local development, a self-hosted orchestrator for scheduling, and either a self-hosted docs site or a dbt Platform subscription once documentation, governance, and cross-team scale start to matter.
Warehouse & lakehouse adapters
dbt's adapter model means "how is dbt implemented on X" is really "what does the dbt-X adapter do differently." A few platform-specific things worth knowing cold:
| Platform | Adapter | Notable specifics |
|---|---|---|
| Snowflake | dbt-snowflake | First-class support for merge incremental strategy, native materialized views, Snowpark Python models, and query tagging for cost attribution back to dbt models. |
| Databricks | dbt-databricks | Runs models on SQL Warehouses or all-purpose clusters; supports Python models natively (PySpark DataFrames), Delta Lake incremental strategies (merge, replace_where), and Unity Catalog-aware three-level namespacing. |
| BigQuery | dbt-bigquery | Partition/cluster config directly in config(); insert_overwrite incremental strategy maps onto BigQuery's partition replacement; strong integration with GCP IAM and cost controls (bytes billed warnings). |
| Redshift | dbt-redshift | Distkey/sortkey configuration surfaced in model config; thread counts matter more here due to Redshift's more limited concurrency model. |
| Fabric / Synapse / SQL Server | dbt-fabric, dbt-synapse | Community/partner-maintained; growing fast alongside Microsoft Fabric's lakehouse push; T-SQL dialect quirks (no native MERGE parity in older SQL Server versions) show up in incremental strategy choice. |
| Postgres | dbt-postgres | The reference adapter dbt Core ships against; common for smaller teams, side projects, and this guide's free-stack example below. |
| DuckDB | dbt-duckdb | Community adapter; runs entirely in-process against local files or object storage (Parquet/CSV/Iceberg) — no server at all, ideal for learning, testing, and small-data production use. |
Orchestration and the surrounding stack
Because dbt Core has no built-in scheduler, "how is dbt implemented" in a real company is as much about what wraps it as the transformations themselves:
- Airflow — the most common enterprise choice; typically invoked via
BashOperator/KubernetesPodOperatorrunning the dbt CLI, or thecosmospackage (Astronomer), which parsesmanifest.jsonand renders each dbt model as its own Airflow task for granular retries and observability. - Dagster — has particularly deep native dbt integration (
dagster-dbt) that treats each dbt model as a software-defined asset, unifying dbt's DAG with upstream ingestion and downstream ML assets in one lineage graph. - Prefect, GitHub Actions/GitLab CI (cron-triggered), and dbt Platform's own job scheduler are the other common choices, roughly in increasing order of "do less infrastructure yourself."
Running dbt for Free — the Open-Source Stack
A complete, zero-license-cost dbt setup you can actually build and demo.
Every piece of a production-grade dbt setup has a free, open-source equivalent. This is a good architecture to describe in an interview if asked "how would you stand up dbt with no budget," and it's genuinely how a lot of side projects, portfolios, and early-stage startups run.
| Layer | Free option | Notes |
|---|---|---|
| Warehouse | DuckDB, Postgres, SQLite (via community adapter), or a free-tier Snowflake/BigQuery trial | DuckDB needs no server and runs off local Parquet/CSV files or an embedded file — the fastest path to "dbt actually running." |
| Transformation engine | dbt Core / dbt Fusion CLI | Fully free regardless of warehouse; install via pip or the standalone CLI installer. |
| Version control | Git + GitHub/GitLab free tier | Branching, pull requests, and code review — the whole point of treating analytics like software. |
| CI/CD | GitHub Actions (free minutes) or GitLab CI | Run dbt build and sqlfluff lint on every PR; use --select state:modified+ against a stored prod manifest for slim CI without a paid platform. |
| Orchestration/scheduling | Dagster OSS, Airflow (self-hosted), or a scheduled GitHub Actions workflow | Dagster's OSS tier has the most turnkey dbt integration for a solo/small-team setup. |
| Docs & lineage | dbt docs generate + GitHub Pages | dbt docs generate produces a static site; publish it free on GitHub Pages or Netlify. |
| Data quality | dbt's built-in tests + dbt_utils / dbt_expectations packages | Both packages are free and cover the vast majority of what commercial data-quality tools charge for. |
| Extract/Load | Airbyte OSS, Meltano, or a simple Python script | Needed only if you're simulating a real ELT pipeline rather than hand-loading seed CSVs. |
| BI / consumption | Metabase OSS, Apache Superset, Evidence.dev | All three read directly from your warehouse and are free to self-host. |
# 1. install dbt with the DuckDB adapter — no server, no account, no cost
pip install dbt-duckdb
# 2. scaffold a project
dbt init jaffle_shop
# 3. profiles.yml points at a local DuckDB file
# jaffle_shop:
# target: dev
# outputs:
# dev:
# type: duckdb
# path: jaffle_shop.duckdb
# 4. build everything: run models, execute tests, in dependency order
dbt build
# 5. generate and preview documentation + lineage graph, fully offline
dbt docs generate
dbt docs serve
It shows you understand that dbt's value (testing, docs, version control, modular SQL) is decoupled from any vendor's billing model — the paid products sell convenience and governance at scale, not capability you can't get for free at small scale.
Use Case Examples
Concrete scenarios you can reference instead of speaking in abstractions.
1. Building a single source of truth for revenue
Raw order and payment data lands from Stripe and an internal orders database via Fivetran. Staging models clean and standardize both. An intermediate model joins orders to payments and refunds. A fct_revenue mart in the marts layer applies the business's official revenue-recognition rule once, tested with not_null/relationships tests and a singular test asserting revenue never goes negative. Every dashboard and every analyst query points at that one mart — eliminating the classic "your revenue number doesn't match my revenue number" meeting.
2. Slowly changing dimensions for a customer 360 view
A CRM's customers table is mutable — a customer's plan, region, or status changes over time, and the CRM only stores current state. A dbt snapshot captures every change with valid-from/valid-to timestamps, letting finance answer "what plan was this customer on when they churned" — a question the raw source system literally cannot answer on its own.
3. Governed self-service metrics via the Semantic Layer
Marketing, finance, and product each had a spreadsheet-specific definition of "active user." A semantic model defines active_users once, with explicit dimensions (channel, plan, region) and grain, and every BI tool queries that single governed metric instead of re-deriving it — the Semantic Layer becomes the contract between the data team and every downstream consumer.
4. Multi-team scale with dbt Mesh
A 200-person company with five data domains (finance, marketing, product, logistics, support) used to share one 4,000-model monolithic dbt project where any team's broken model blocked everyone else's CI. Splitting into domain-owned projects connected by dbt Mesh's cross-project ref() and versioned public models let each team ship independently while still safely depending on each other's certified outputs.
5. Backfilling years of event data with microbatch
A clickstream events table needs three years of historical backfill plus daily incremental loads going forward. A microbatch incremental model, keyed on event_time with a daily batch_size, backfills the full history as independently retryable per-day batches and then runs the same logic daily in production without a second, parallel "backfill" codepath to maintain.
Best Practices & Conventions
The house style most well-run dbt projects converge on.
- Layer your DAG: staging (1:1 with sources, light cleaning) → intermediate (joins/business logic, not exposed) → marts (wide, consumer-facing). Never let a mart reference a raw source directly.
- One staging model per source table, named
stg_<source>__<table>; one mart per business concept, named for what it is (fct_orders,dim_customers) not how it's built. - Test at the edges hardest: primary keys always get
unique+not_null; foreign keys getrelationships; anything with a fixed vocabulary getsaccepted_values. - Document as you go — a
description:on every mart column pays for itself the first time someone new joins the team; don't let documentation become a quarterly cleanup project. - Use environments properly: every developer builds into their own dev schema; CI builds into an ephemeral schema using state comparison against prod; only the scheduled prod job writes to the schemas BI tools query.
- Prefer
ref()/source()over hard-coded table names, always, with no exceptions — it's the single convention the entire dependency graph, environment promotion, and state-based CI selection depends on. - Keep macros DRY but readable — a macro used once isn't worth the indirection; three or more near-duplicate blocks of SQL usually is.
- Lint and format SQL (commonly with
sqlfluff) in CI so style-only comments never happen in code review. - Version your public/cross-team models once other teams depend on them, so you can evolve a model's contract without breaking downstream consumers overnight.
Interview Questions & Answers
Organized from fundamentals to systems-design-style scenario questions. Click any question to expand.
Fundamentals
fundamentalsWhat problem does dbt solve, and what does it deliberately not do?
dbt solves the "T" in ELT: turning raw, loaded data into tested, documented, version-controlled transformations using SQL, with software-engineering discipline (git, CI, code review, modularity) applied to analytics code. It deliberately does not extract or load data, does not schedule itself outside of dbt Platform, is not a database, and is not a BI tool — it assumes those exist around it.
fundamentalsWhat does ref() actually do, and why does it matter more than it looks like it should?
ref() resolves to the correct fully-qualified table/view name for the current environment/target at compile time, and simultaneously registers a dependency edge in dbt's DAG. Because of it, the same model code builds into a developer's personal dev schema, a CI schema, or production without any manual find-and-replace, and dbt can compute exact build order and which downstream models are affected by any change — the entire state-based selection system (state:modified+) depends on this graph being accurate.
fundamentalsExplain the difference between a view, a table, and an incremental materialization, and how you'd choose between them.
A view materialization creates a database view — cheap to build, always reflects current underlying data, but recomputes on every query, so it's a poor choice for something queried thousands of times a day. A table fully rebuilds a physical table on every dbt run — faster to query, more expensive/slower to build, appropriate for marts under heavy BI load where you can tolerate periodic full rebuilds. Incremental only processes new/changed rows after the first run, trading some fragility (you must get the filtering and merge logic right, and full-refreshes still cost the full rebuild) for dramatically lower build time and cost on very large, append-heavy tables. The decision usually comes down to table size and how expensive a full rebuild is relative to your refresh SLA.
fundamentalsWhat's the difference between a generic test and a singular test?
A generic (schema) test is a parameterized, reusable macro applied declaratively in YAML — unique, not_null, accepted_values, relationships, or custom ones from packages like dbt_expectations. A singular test is a standalone .sql file in tests/ that returns rows dbt treats as failures — used for one-off business logic assertions too specific to generalize, like "gross margin should never exceed 100%."
fundamentalsWhat is dbt_project.yml versus profiles.yml, and why are they separate files?
dbt_project.yml defines the project itself — its name, model paths, default materializations and configs — and lives in and is committed to the git repository. profiles.yml holds connection credentials and target definitions and deliberately lives outside the repo (typically in ~/.dbt/) so secrets never get committed to version control; dbt Platform replaces this file with UI-managed, encrypted connection settings per environment.
Intermediate
intermediateWalk through what happens, step by step, when you run dbt run.
dbt parses every SQL and YAML file in the project into an internal graph and writes it to manifest.json; it then compiles each selected model's Jinja into pure SQL (written to target/compiled); it topologically sorts the DAG and executes nodes against the warehouse in dependency order, in parallel up to the configured thread count, wrapping each model's SELECT in the DDL/DML its materialization requires; finally it writes run_results.json with per-model status and timing. Note dbt run only runs models — tests, snapshots, and seeds need dbt test/dbt snapshot/dbt seed, or all of it together via dbt build, which interleaves models and their tests so a failing test can block dependents immediately.
intermediateHow would you design a slowly changing dimension in dbt?
Use a snapshot pointed at the mutable source table with either a timestamp strategy (if the source has a reliable "updated_at" column) or a check strategy (comparing specific columns when no reliable timestamp exists). dbt appends a new row with dbt_valid_from/dbt_valid_to every time it detects a change, giving you full Type-2 history without hand-rolled merge logic. Downstream marts then join to the snapshot on a valid-at-a-point-in-time predicate when historical accuracy matters, or to the latest row when only current state is needed.
intermediateWhat is state:modified and why does it matter for CI?
dbt can compare the current project's manifest against a previously stored manifest (typically production's) and compute exactly which nodes changed, plus everything downstream of them (state:modified+). CI pipelines use this via --select state:modified+ --defer --state ./prod-manifest to build and test only the affected subset of the DAG against a temporary schema, deferring unaffected models to their already-built production versions — turning a CI run that would otherwise rebuild thousands of models into one that rebuilds a handful, in minutes instead of hours.
intermediateWhen would you reach for an ephemeral materialization, and what's the risk?
Ephemeral models are appropriate for small, single-purpose logic reused by a couple of downstream models where you don't want warehouse clutter or extra permission surface — a currency-conversion CTE, for instance. The risk is that ephemeral models are inlined as CTEs wherever referenced, so overusing them (or nesting them deeply) bloats compiled SQL, makes query plans harder to reason about, and makes debugging painful because you can't query the ephemeral model directly to inspect its output.
intermediateHow does dbt handle secrets and environment-specific configuration?
Connection credentials live in profiles.yml (dbt Core), which is git-ignored and typically templated with environment variables ({{ env_var('SNOWFLAKE_PASSWORD') }}) so credentials never touch source control; dbt Platform instead stores encrypted credentials per environment in its own settings UI. Non-secret environment differences (which schema to build into, which Slack channel to alert) are handled via dbt's target.name variable and Jinja conditionals, or dbt Platform's environment variables feature.
Advanced / scenario
advancedA fact table has grown to 50 billion rows and nightly full-refresh builds now take six hours. Walk through how you'd fix it.
First confirm it's actually incremental-shaped data (append-mostly, with a reliable event-time column) — if so, convert it to an incremental model, likely with the merge or microbatch strategy depending on whether updates to old rows happen. Partition/cluster the underlying table on the event-time column so the warehouse can prune scanned data at query time as well as at write time. Check thread count and warehouse sizing aren't the bottleneck. If historical corrections are common, consider microbatch specifically, since it isolates each time batch as its own retryable unit rather than one giant merge statement. Finally, validate the switch doesn't silently break anything downstream that assumed a full rebuild (e.g., late-arriving data that the incremental filter would now miss) — this is the most common way incremental migrations introduce silent data quality bugs.
advancedHow would you migrate a single 3,000-model dbt monolith into a multi-project architecture without a "big bang" cutover?
Identify domain boundaries by ownership, not just folder structure — the teams that already work independently are the natural project boundaries. Pick one domain to extract first, ideally one with few inbound dependents. Stand it up as its own project, use dbt Mesh's cross-project ref() so the remaining monolith can still depend on the extracted project's now-public, versioned models, and add contracts to those public models so the interface is stable while internals keep evolving independently. Repeat domain by domain, always keeping the monolith able to consume the already-extracted projects, so there's no moment where everything has to move at once.
advancedTwo teams both compute "monthly active users" and get different numbers. How does dbt's tooling help you actually fix this, not just patch it once?
Patching the immediate discrepancy is a one-time fix; the durable fix is moving the metric definition out of individual dashboards and SQL files entirely and into a single governed semantic model + metric definition in the Semantic Layer, with explicit dimensions and grain. Every BI tool and analyst then queries that one definition through the Semantic Layer's query interface instead of re-deriving the aggregation logic, so a future definitional change (say, redefining "active" to require two sessions instead of one) happens once and propagates everywhere consistently, and would show up as a reviewable diff in the metric's YAML rather than a silent divergence.
advancedWhat are dbt unit tests, and how are they different from the schema tests most people are used to?
Schema tests (unique, not_null, etc.) assert on data that's actually sitting in the warehouse after a model runs — they catch bad data, but only after you've built the model and only against whatever rows currently exist. Unit tests instead mock a small set of input rows, run the model's actual SQL logic against them, and assert on the expected output rows — testing the logic in isolation, the way a software unit test does, independent of what real data happens to contain. They catch a broken CASE statement or join condition before it ever touches production data, and they're the piece that was historically the biggest gap between dbt's "testing" story and what software engineers mean by the word.
advancedWhat's the practical difference between dbt Fusion and the classic dbt Core execution engine?
Classic dbt Core treats SQL as an opaque string: it compiles Jinja and hands the result to the warehouse, discovering syntax or reference errors only when the warehouse rejects the query. Fusion, written in Rust, natively parses and understands SQL across dialects, so it can validate queries, resolve column-level lineage, and power IDE features like autocomplete and inline error detection before a single query hits the warehouse — shortening the feedback loop from "wait for a warehouse round-trip" to "instant, local." It's a drop-in replacement for the same dbt project and YAML — the language doesn't change, the engine underneath it does.
Behavioral / architecture judgment
judgmentHow do you decide what belongs in staging versus intermediate versus marts?
Staging models answer "what does this raw source table look like, cleaned up" — one in, one out, no joins across sources. Intermediate models answer "what reusable piece of business logic sits between raw data and a final answer" — joins, aggregations, deduplication — but are deliberately not exposed to BI tools, because they're implementation detail. Marts answer "what does the business actually want to query" — a wide, denormalized, well-named, well-tested table that a non-technical analyst could understand without reading the SQL behind it. If you find yourself putting a join with real business meaning into a staging model, or exposing an intermediate model directly to a dashboard, that's usually the signal the layering has drifted.
judgmentA stakeholder wants a new dashboard by end of week; building it "the right way" (proper staging/marts/tests) will take two. What do you do?
Be explicit about the trade-off rather than silently picking one side: a fast, minimally-tested model gets something in front of the stakeholder on time but accrues technical debt and risk of a wrong number reaching a decision-maker; the fully modeled version is slower but durable. A reasonable middle path is to ship a narrowly-scoped mart with the two or three tests that would actually catch a wrong number (uniqueness of the grain, a sane range check), flag it explicitly as provisional in the dbt description/exposure, and schedule the proper staging/intermediate refactor as immediate follow-up work rather than "eventually." The judgment being tested isn't SQL — it's whether you communicate the trade-off instead of hiding it.
judgmentHow would you convince a team resistant to "treating analytics like software" (git, PRs, tests) to adopt dbt properly?
Lead with a concrete failure they've already lived through — a bad number that reached an executive dashboard, a report that broke silently when a source schema changed — and show how a specific dbt feature (a not_null test, a source freshness check, a PR diff on a model) would have caught it before it shipped. Abstract arguments about "engineering discipline" tend to land poorly with analysts who see it as process overhead; a story about a real incident and the five-line YAML change that prevents its recurrence usually lands.
CLI Cheat Sheet
The commands and selectors you'll actually type.
| Command | What it does |
|---|---|
| dbt run | Executes models (not tests, not seeds, not snapshots) |
| dbt test | Runs schema + singular + unit tests |
| dbt build | Runs seeds, snapshots, models, and tests together, in DAG order — the command most CI pipelines actually use |
| dbt seed | Loads CSVs from seeds/ as tables |
| dbt snapshot | Executes SCD Type 2 snapshot logic |
| dbt docs generate | Builds catalog.json + static documentation site |
| dbt docs serve | Serves the generated docs site locally |
| dbt compile | Compiles Jinja to SQL without executing anything against the warehouse |
| dbt source freshness | Checks how stale declared source tables are against configured thresholds |
| dbt deps | Installs packages declared in packages.yml |
| dbt ls | Lists selected resources without running them — useful for sanity-checking a --select expression |
Node selection syntax
| Selector | Meaning |
|---|---|
| --select stg_payments | Just that one model |
| --select stg_payments+ | That model and everything downstream of it |
| --select +fct_orders | That model and everything upstream of it |
| --select tag:finance | All models tagged finance |
| --select path:models/marts | Everything under that folder path |
| --select state:modified+ | Changed models (vs. a stored manifest) plus downstream dependents — the backbone of slim CI |
| --exclude tag:deprecated | Runs everything selected except what's excluded |
| --full-refresh | Forces incremental models to fully rebuild |
Jinja quick reference
{{ ref('model_name') }} # dependency on another model
{{ source('source_name', 'table') }} # dependency on a raw source table
{{ config(materialized='table') }} # per-model configuration
{{ this }} # the current model's own relation (used in incremental filters)
{{ var('my_var', 'default') }} # project variable with a fallback
{% if is_incremental() %} ... {% endif %} # only compiled during incremental runs
{{ dbt_utils.generate_surrogate_key(['a','b']) }} # common dbt_utils macro
Glossary
Every term used in this guide, in one place.
- Adapter
- A plugin (e.g. dbt-snowflake) that translates dbt's warehouse-agnostic logic into a specific database's SQL dialect and connection behavior.
- Analyses
- Ad hoc .sql files that get compiled by dbt but are never materialized or run — useful for one-off exploratory queries kept under version control.
- Contract
- An enforced, declared column-level schema on a model; a breaking change to the model's shape fails the build instead of silently propagating.
- DAG
- Directed acyclic graph — the dependency structure dbt builds from every ref()/source() call, used to determine build order.
- dbt Core
- The free, open-source command-line dbt project and (historically) execution engine.
- dbt Fusion
- dbt Labs' newer, Rust-based execution engine with native SQL comprehension across dialects; now the default engine, built on an Apache-2.0 open core.
- dbt Mesh
- A set of features (cross-project ref(), groups, access modifiers, versioned contracts) enabling multiple independently-owned dbt projects to safely depend on each other.
- dbt Platform
- dbt Labs' commercial, hosted product (the current name for what was marketed as "dbt Cloud") — adds scheduling, a hosted IDE, governance, and the hosted Semantic Layer.
- Ephemeral model
- A materialization that isn't built as a database object at all; inlined as a CTE wherever it's referenced.
- ELT
- Extract, Load, Transform — the pattern dbt assumes: raw data lands in the warehouse first, and transformation happens in-database afterward.
- Exposure
- A YAML declaration that a dashboard, application, or ML pipeline depends on specific dbt models, extending lineage visibility past the warehouse.
- Generic test
- A reusable, parameterized test (e.g. unique, not_null) applied declaratively in YAML.
- Hook
- Arbitrary SQL configured to run before/after a model (pre-hook/post-hook) or an entire invocation (on-run-start/on-run-end).
- Incremental model
- A materialization that processes only new or changed rows on subsequent runs instead of rebuilding the full table.
- Jinja
- The Python templating language dbt compiles every model through, enabling ref(), macros, and control flow inside SQL files.
- Macro
- A reusable, parameterized snippet of Jinja/SQL logic — dbt's equivalent of a function.
- Manifest
- manifest.json — the full JSON graph of a dbt project's models, tests, sources, and macros; the backbone of docs, lineage, and state-based selection.
- Mart
- A wide, business-defined, consumer-facing model intended for direct use by BI tools and analysts.
- Materialization
- The strategy that determines what SQL a model's SELECT statement is wrapped in: view, table, incremental, ephemeral, materialized view, or snapshot.
- MetricFlow
- The query-compilation engine behind the dbt Semantic Layer that turns a metric + requested dimensions into optimized SQL.
- Microbatch
- An incremental strategy that splits loads into independently retryable, time-partitioned batches based on a declared event_time column.
- Model
- A single .sql (or Python) file containing one query, which dbt turns into a view, table, or other warehouse object.
- Package
- An installable library of dbt macros and/or models, declared in packages.yml (e.g. dbt_utils, dbt_expectations).
- ref()
- The Jinja function that references another dbt model, resolving to the correct environment-specific table name and registering a DAG dependency edge.
- Seed
- A small, static CSV file in the seeds/ directory that dbt loads into the warehouse as a table.
- Semantic Layer
- dbt's governed metrics layer, letting a metric be defined once and queried consistently by any connected BI tool.
- Singular test
- A one-off .sql file in tests/ asserting business logic too specific to generalize into a schema test.
- Snapshot
- A materialization implementing Type-2 slowly-changing-dimension history tracking over a mutable source table.
- source()
- The Jinja function referencing a declared raw table, marking the starting point of the DAG and enabling source freshness checks.
- Staging model
- A model that is 1:1 with a raw source table, applying only light cleaning, renaming, and type casting.
- State comparison
- Comparing the current manifest to a previously stored one to identify changed nodes (state:modified), enabling slim/incremental CI runs.
- Target
- A named environment/connection configuration (e.g. dev, prod) that a dbt invocation runs against.
- Unit test
- A test that mocks input rows and asserts on a model's expected output, validating SQL logic independent of real warehouse data.