Data Engineering for AnalyticsVol. 21 · Analytics
0 / 0

Shelves / Data Engineering for Analytics

DE·04

Transformations as Code: ELT and dbt

Why modern analytics loads raw data first and transforms it inside the warehouse, and how dbt turns those transformations into a tested, documented, version-controlled software project: sources and refs, the dependency graph, materialisations (view, table, incremental, ephemeral), snapshots for history, data tests and unit tests, documentation and lineage, macros and packages, environments and CI that builds only what changed; with a lab in which a test catches 37 replayed payments before they reach a revenue table, and an incremental model turns out to save less than expected.

18 topics · ~9 min read · 16-question quiz
Updated Suggest a correction

Start here: SQL as software

For years, analytics transformations lived in scheduled SQL scripts nobody dared touch, or in ETL tools' visual workflows. When a number looked wrong, nobody could say which script produced it, whether it was tested, or what else depended on it.

Two shifts changed that:

  • ELT instead of ETL. Cloud warehouses are cheap and fast enough to load raw data first (extract, load) and transform inside the warehouse with SQL (transform). Raw data stays available for reprocessing.
  • Transformations as code. dbt treats each transformation as a model: a SELECT in a file, under version control, with declared dependencies, tests and documentation. dbt compiles the project into SQL, runs it in dependency order, and records lineage.
Text
sources (raw tables) → staging models → intermediate models → marts (facts, dimensions)
              each arrow is a ref(); dbt builds them in order, testing as it goes

What the lab caught

A dbt project over chapter 01's orders ran 9 nodes (2 staging views, 6 tests, 1 revenue model) in under 2 seconds on DuckDB. A replayed payment webhook had duplicated 37 payments:

Result
unique test on stg_payments.payment_id FAIL 37
revenue model downstream of the failing test skipped, never built with bad data
revenue error the duplicates would have caused ₹8,778
after deduplicating in staging (qualify row_number() … = 1) all 9 pass

An incremental version of the revenue model (process only recent days) took 1.12 s instead of 1.6 s for a full rebuild: less than expected, because the staging view it read from still deduplicated all payments every time. Incremental only helps if the expensive work upstream is incremental too.

How deep to go

Volume 17 defines six mastery levels. For ELT and dbt:

Level What you can do
L1 Explain ELT and what dbt models, refs and tests are
L2 Build a dbt project with sources, staging, marts and tests
L3 Explain materialisations, incremental strategies, snapshots and the dependency graph
L4 Debug wrong numbers through lineage; fix slow or incorrect incremental models
L5 Design a project's structure, conventions, testing strategy and CI for a team
L6 Run it at scale: hundreds of models, ownership, cost, contracts between teams

A dbt project

Text
tiffinbox_analytics/
  dbt_project.yml            # name, paths, default materialisations per folder
  models/
    staging/                 # one model per source table: stg_orders, stg_payments …
      sources.yml            # raw tables, freshness rules
      schema.yml             # tests and docs for staging models
    intermediate/            # reusable building blocks: int_order_journeys
    marts/
      finance/               # fct_payments, fct_daily_kitchen_revenue
      operations/            # fct_deliveries, dim_rider
  snapshots/                 # dim_kitchen history (type 2)
  seeds/                     # small static CSVs: festival calendar, area mapping
  macros/                    # reusable SQL: paise_to_rupees(), generate_schema_name()
  tests/                     # singular tests: revenue reconciles with the payment provider

A model:

SQL
-- models/marts/finance/fct_daily_kitchen_revenue.sql
{{ config(materialized='incremental', unique_key=['kitchen_id','order_date'],
          incremental_strategy='delete+insert') }}
select o.kitchen_id, o.order_date, count(*) as orders, sum(p.amount_paise) as revenue_paise
from {{ ref('stg_orders') }} o
join {{ ref('stg_payments') }} p using (order_id)
where o.status = 'delivered'
{% if is_incremental() %}
  and o.order_date >= (select max(order_date) - interval 2 day from {{ this }})
{% endif %}
group by 1, 2

ref() declares dependencies; {{ this }} refers to the model's existing table; the incremental filter reprocesses the last two days to catch late-arriving data.

Materialisations

Materialisation Built as Use for
view a view; computed on every read staging, light logic
table rebuilt in full each run marts of moderate size; anything whose logic changes often
incremental inserts/merges only new or changed rows large facts; append-mostly events
ephemeral inlined as a CTE into downstream models small reusable steps
materialised view (adapter-dependent) maintained by the warehouse near-real-time aggregates where supported

Incremental strategies: append (fast; duplicates on reruns), merge / delete+insert on a unique_key (idempotent), insert_overwrite by partition (idempotent and cheap on partitioned tables), microbatch (process fixed time slices independently, with built-in backfills). Choose an idempotent one, reprocess a lookback window for late data, and plan full refreshes when logic changes. The lab's lesson applies: if an upstream view does the heavy work over all data, the incremental model inherits that cost.

Snapshots

YAML
snapshots:
  - name: snap_kitchens
    relation: source('raw', 'kitchens')
    config: {unique_key: kitchen_id, strategy: check, check_cols: [area, rating_tier]}

Each run compares current rows with the last snapshot and adds versions with dbt_valid_from and dbt_valid_to: chapter 02's type 2 dimension without hand-written merge logic. Snapshot raw data, as early as possible, because history not captured can't be recovered.

Tests

  • Generic data tests in YAML: unique and not_null on every grain key, accepted_values on enumerations, relationships for foreign keys, plus packages (dbt-utils, dbt-expectations) for ranges, recency and row-count comparisons.
  • Singular tests: a SQL file returning rows that violate a rule ("daily revenue reconciles with the payment provider's settlement within ₹1").
  • Unit tests (dbt 1.8+): fixed input rows and expected output for a model's logic, run without production data. Use them for tricky logic: SCD handling, refunds netting, time-zone conversions.
  • Severity and thresholds: warn versus error, and error_if: ">10" for tests where a few violations are tolerable.
  • Model contracts: enforce column names and types on public models so downstream teams can rely on them.

dbt build interleaves models and tests in graph order, so a failing test stops its downstream models (the lab).

Documentation and lineage

Descriptions in YAML plus dbt docs generate produce a browsable site with every model's columns, tests and the lineage graph from sources to dashboards (exposures). When a number looks wrong, lineage is how you find which upstream model and source it came from.

Macros, packages and Jinja

Macros remove repetition ({{ paise_to_rupees('amount_paise') }}), adapt SQL to environments (schema naming), and generate tests. Packages share them across projects. Keep macros small and tested: a clever macro that nobody understands is a new legacy script.

Environments and CI

  • Each developer builds into their own schema (dbt_kalyan), CI into a temporary schema, production into analytics.
  • Slim CI: on a pull request, dbt build --select state:modified+ --defer --state prod_artifacts builds only changed models and their dependents, reading unchanged upstream models from production.
  • Production runs are scheduled by an orchestrator (chapter 05), with source freshness checks first and alerts on failures.

Common traps

  • Business logic in BI tools instead of models.
  • No tests on grain keys.
  • Incremental models with append that duplicate on reruns, or without a lookback for late data.
  • Snapshots of marts instead of raw sources.
  • Huge models doing everything in one file.

Lab: a dbt project that stops bad data

Setup. dbt Core 1.12 with the dbt-duckdb adapter on the lab machine (the CLI also noted that a newer major version of dbt is available; the concepts here carry over). A DuckDB warehouse file with two raw tables built from chapter 01's data:

  • raw.orders: 4,575,359 orders placed before 1 October 2026.
  • raw.payments: one payment per non-cancelled order (4,117,861 rows), into which 37 payments were duplicated, as a replayed webhook would do.

Models: stg_orders and stg_payments (views); fct_daily_kitchen_revenue (incremental, delete+insert on kitchen_id, order_date, reprocessing the last two days). Tests: unique and not_null on both IDs, accepted_values on status, relationships from payments to orders.

Experiment 1: dbt build with the duplicates

Text
1 of 9 OK created sql view model main.stg_orders
2 of 9 OK created sql view model main.stg_payments
4 of 9 PASS not_null_stg_orders_order_id
3 of 9 PASS accepted_values_stg_orders_status__delivered__cancelled__refunded
6 of 9 PASS not_null_stg_payments_payment_id
5 of 9 PASS unique_stg_orders_order_id
7 of 9 PASS relationships_stg_payments_order_id__order_id__ref_stg_orders_
8 of 9 FAIL 37 unique_stg_payments_payment_id
Finished running 1 incremental model, 6 data tests, 2 view models in 1.86s
Done. PASS=7 WARN=0 ERROR=1 SKIP=1 TOTAL=9

The revenue model was skipped. Had it run, the 37 duplicates would have added ₹8,778 of revenue that never existed.

Experiment 2: fix in staging

stg_payments gained qualify row_number() over (partition by payment_id order by paid_at) = 1. dbt build: PASS=9, revenue model built in 1.68 s.

Experiment 3: incremental vs full refresh

Run Model time
full refresh (all history) 1.59 s
one new day loaded (13,697 orders), incremental run 1.12 s
full refresh again 1.64 s

The final table: 107,200 rows (kitchen × day) through 1 October 2026.

What it shows

  • Tests in the build graph protect consumers: the failing uniqueness test stopped the downstream model, so no dashboard showed inflated revenue.
  • Fix data problems once, in staging, then every model downstream benefits.
  • Incremental models are only as incremental as their inputs. The model filtered to recent days, but its input view deduplicated every payment on each run (a window over 4 million rows), so the run saved only ~30%. Make staging incremental too (or deduplicate in the raw load), and the incremental run would touch only the new day.
  • The delete+insert strategy with a lookback window makes reruns idempotent: running it twice produces the same table.

Try it yourself

  1. Turn stg_payments into an incremental model and remeasure Experiment 3.
  2. Add a dbt unit test for the revenue model with three hand-written orders, including a cancelled one.
  3. Add a snapshot of a raw.kitchens table, change one kitchen's area, run dbt snapshot twice, and query its history.
  4. Add a singular test that compares total revenue with the sum of raw.payments (after deduplication).

Revision sheet: ELT and dbt

Key ideas

  • ELT: load raw, transform in the warehouse; raw stays for reprocessing.
  • dbt: models as SELECTs; source() and ref() build the graph; dbt build runs models and tests in order and skips downstream of failures.
  • Materialisations: view, table, incremental (idempotent strategy + lookback), ephemeral.
  • Snapshots capture type 2 history from raw sources.
  • Tests: generic, singular, unit, contracts; severity thresholds.
  • Docs and lineage for tracing numbers; macros and packages for reuse.
  • Per-developer schemas; slim CI (state:modified+); orchestrated production runs with freshness checks.

Numbers to remember

  • Lab: 37 duplicated payments → unique test failed → revenue model skipped; ₹8,778 of phantom revenue avoided.
  • Incremental 1.12 s vs full 1.6 s, because staging still processed everything.

Glossary

  • Model: a dbt SELECT materialised as a view or table.
  • Materialisation: how dbt builds a model.
  • Snapshot: dbt's type 2 history capture.
  • Lineage: the graph from sources to models to exposures.
  • Slim CI: building only changed models and dependents.