October 16, 2025

Testing dbt Models: From not_null to Premium Reconciliation

The most expensive bugs in insurance reporting aren't the ones that crash a pipeline. They're the ones that quietly drop a few contract sections from an inner join, double-count a resubmitted transaction, or apply last month's exchange rate. The numbers look plausible, and nobody notices until the premium total doesn't match finance at quarter end.

dbt makes testing part of every run instead of something done by hand before go-live. This post covers the kinds of tests I find most useful on insurance data, from the built-in ones to reconciliation checks and dbt's unit tests.

1. Generic tests: the basics on every model

 1: # models/marts/_marts.yml
 2: version: 2
 3: 
 4: models:
 5:   - name: fct_premium
 6:     columns:
 7:       - name: premium_id
 8:         tests: [unique, not_null]
 9:       - name: contract_section_key
10:         tests:
11:           - not_null
12:           - relationships:
13:               to: ref('dim_section')
14:               field: contract_section_key
15:       - name: broker_key
16:         tests:
17:           - relationships:
18:               to: ref('dim_broker')
19:               field: broker_key
20:       - name: transaction_type
21:         tests:
22:           - accepted_values:
23:               values: ['NEW', 'RENEWAL', 'MTA', 'CANCELLATION']
24:       - name: original_ccy
25:         tests:
26:           - not_null
27:           - accepted_values:
28:               values: ['GBP', 'USD', 'EUR', 'CAD', 'AUD']
29:               config:
30:                 severity: warn

The relationships tests are the most valuable here. They catch orphaned transactions, rows whose contract section or broker doesn't exist in the dimension, before an inner join drops them from a report.

The currency test is set to warn. A new currency isn't necessarily wrong, but someone should look at it.

2. Singular tests: business rules in SQL

A singular test is a SQL file in the tests/ folder that returns the rows that break a rule. No rows means a pass.

1: -- tests/assert_expiry_after_inception.sql
2: select certificate_ref, umr, section_no, inception_date, expiry_date
3: from {{ ref('fct_risks') }}
4: where expiry_date < inception_date
1: -- tests/assert_cancellations_are_negative.sql
2: select premium_id, transaction_type, gross_premium
3: from {{ ref('fct_premium') }}
4: where transaction_type = 'CANCELLATION'
5:   and gross_premium > 0
1: -- tests/assert_risk_within_contract_period.sql
2: select r.certificate_ref, r.risk_inception_date, cs.inception_date, cs.expiry_date
3: from {{ ref('fct_risks') }} r
4: join {{ ref('dim_section') }} cs
5:   on cs.contract_section_key = r.contract_section_key
6: where r.risk_inception_date < cs.inception_date
7:    or r.risk_inception_date >  cs.expiry_date

That last one is a real data quality rule for delegated authority: a risk bound outside the binding authority's period is something the oversight team needs to know about.

3. Reconciliation tests: do the totals match the source?

Row-level tests don't catch a join that duplicates rows or a filter that drops a whole month. For that, compare totals between the source and the final model. Most of the migration and reporting work I've done ends with this kind of reconciliation, and it's worth automating rather than doing in a spreadsheet.

 1: -- tests/reconcile_premium_to_source.sql
 2: with source_totals as (
 3:     select year_of_account, bordereau_month,
 4:            count(*)            as row_count,
 5:            sum(gross_premium)  as gross_premium
 6:     from {{ ref('stg_premium') }}
 7:     group by 1, 2
 8: ),
 9: model_totals as (
10:     select cs.year_of_account, f.bordereau_month,
11:            count(*)              as row_count,
12:            sum(f.gross_premium)  as gross_premium
13:     from {{ ref('fct_premium') }} f
14:     join {{ ref('dim_section') }} cs
15:       on cs.contract_section_key = f.contract_section_key
16:     group by 1, 2
17: )
18: select
19:     coalesce(s.year_of_account, m.year_of_account) as year_of_account,
20:     coalesce(s.bordereau_month, m.bordereau_month) as bordereau_month,
21:     s.row_count     as source_rows,   m.row_count     as model_rows,
22:     s.gross_premium as source_gwp,    m.gross_premium as model_gwp
23: from source_totals s
24: full outer join model_totals m
25:   on  m.year_of_account = s.year_of_account
26:   and m.bordereau_month = s.bordereau_month
27: where coalesce(s.row_count, 0) <> coalesce(m.row_count, 0)
28:    or abs(coalesce(s.gross_premium, 0) - coalesce(m.gross_premium, 0)) > 0.01

Any row returned shows exactly which year of account and month is out, by how many rows, and by how much premium. Compare in the original currency, so currency conversion problems don't hide counting problems.

4. Unit tests: logic with fixed inputs (dbt 1.8+)

The tests above check real data. Unit tests check logic with small, fixed inputs, before the model ever runs against production data. They're ideal for calculations like signing cancellations or netting off commission and brokerage:

 1: # models/marts/_unit_tests.yml
 2: unit_tests:
 3:   - name: net_premium_signs_cancellations_and_deducts_deductions
 4:     model: fct_premium
 5:     given:
 6:       - input: ref('stg_premium')
 7:         rows:
 8:           - {certificate_ref: C1, umr: B1, section_no: S1, transaction_type: NEW,          gross_premium: 1000, commission_pct: 25, brokerage_pct: 5, original_ccy: GBP, bordereau_month: 2025-09-01}
 9:           - {certificate_ref: C2, umr: B1, section_no: S1, transaction_type: CANCELLATION, gross_premium: 400,  commission_pct: 25, brokerage_pct: 5, original_ccy: GBP, bordereau_month: 2025-09-01}
10:       - input: ref('dim_section')
11:         rows:
12:           - {contract_section_key: 10, umr: B1, section_no: S1, coverholder_key: 1, broker_key: 1}
13:       - input: ref('stg_fx_rates')
14:         rows:
15:           - {currency: GBP, roe_month: 2025-09-01, rate_to_gbp: 1}
16:     expect:
17:       rows:
18:         - {certificate_ref: C1, gross_premium: 1000, commission: 250,  brokerage: 50,  net_premium: 700}
19:         - {certificate_ref: C2, gross_premium: -400, commission: -100, brokerage: -20, net_premium: -280}

You only list the columns the test cares about. dbt fills the rest. Run unit tests in development and CI. They don't need to run in production, because the inputs never change.

5. Source freshness

A pipeline that runs perfectly on yesterday's data is still wrong. Freshness checks on sources catch a feed that has stopped arriving:

1: sources:
2:   - name: feed
3:     tables:
4:       - name: claims
5:         loaded_at_field: loaded_at
6:         freshness:
7:           warn_after:  {count: 1, period: day}
8:           error_after: {count: 3, period: day}

Making failures useful

  • store_failures: true writes the failing rows to a table, so you can query them, or put them in a report for whoever needs to fix the data.
  • Severity and thresholds: warn_if: ">0" and error_if: ">100" let a test warn on a handful of bad rows and fail only when something is badly wrong.
  • dbt build runs tests straight after each model and skips downstream models when a test errors, so bad data doesn't reach reporting.

Where to start

If a project has no tests at all, I'd add them in this order: unique and not_null on every key, relationships from facts to dimensions, one reconciliation test per fact table, and source freshness. That's a small amount of YAML and SQL, and it catches most of the problems that would otherwise surface in a finance meeting.

August 14, 2025

dbt Snapshots: Tracking Coverholder History with SCD Type 2

Some questions can only be answered with history. Was this coverholder approved when the risk incepted? Which broker was on the contract section when the claim was notified? What was the commission rate before it was renegotiated? If your dimension tables only hold current values, those answers are gone.

In SSIS we built Slowly Changing Dimension Type 2 logic by hand, and later as MERGE statements. In dbt, the same job is done by snapshots. This post shows how to use them for insurance reference data, including the YAML configuration introduced in dbt 1.9, and the traps to avoid.

How a snapshot works

A snapshot looks at a source table each time it runs, compares each row with what it stored last time, and:

  • inserts new rows with dbt_valid_from set and dbt_valid_to null,
  • for changed rows, closes the old version by setting dbt_valid_to and inserts a new version,
  • leaves unchanged rows alone.

The result is a full Type 2 history table, maintained by dbt.

Defining a snapshot in YAML (dbt 1.9+)

From dbt 1.9, snapshots can be defined entirely in YAML, next to your models:

 1: # snapshots/coverholder_snapshot.yml
 2: snapshots:
 3:   - name: coverholder_snapshot
 4:     relation: source('feed', 'coverholder')
 5:     config:
 6:       schema: snapshots
 7:       unique_key: coverholder_id
 8:       strategy: check
 9:       check_cols: ['coverholder_name', 'country', 'approval_status', 'oversight_rating']
10:       hard_deletes: invalidate

In older versions, the same thing is a {% snapshot %} block in a .sql file. It still works, but the YAML version is shorter and easier to review.

Choosing a strategy

timestamp uses an "updated at" column. If the source row's timestamp is newer than the stored version, it's a change:

1:     config:
2:       unique_key: [umr, section_no]
3:       strategy: timestamp
4:       updated_at: last_modified_at

It's efficient and reliable, but only if the source really updates that column every time something changes. Plenty of systems don't.

check compares the listed columns directly. It's slower on very wide or large tables, but it doesn't depend on the source system behaving. For reference data from a feed, where I can't be sure an update timestamp is maintained, I use check with an explicit column list.

Avoid check_cols: all unless you really mean it. If the source has a load timestamp or a batch ID that changes on every delivery, every row will look changed and you'll get a new version of every coverholder every day.

Deletes

By default, a row that disappears from the source stays "current" in the snapshot forever. hard_deletes: invalidate (dbt 1.9+) closes it instead, and new_record goes further and adds a row marking the deletion. For a coverholder that's been removed from the register, invalidate is usually what you want.

Only do this if the source is a complete extract. If the source table only holds changes, every coverholder missing from today's delivery would be closed.

Snapshot raw data, not models

Snapshot the source as close to raw as you can, before business logic. If you snapshot the output of a model and later change the model's logic, the snapshot will record a "change" for every row, and you can't recreate the true history. Apply cleaning in a model that reads from the snapshot instead.

Building the dimension

The snapshot itself isn't the dimension. A model on top of it adds a surrogate key and friendlier column names:

 1: -- models/marts/dim_coverholder.sql
 2: select
 3:     {{ dbt_utils.generate_surrogate_key(['coverholder_id', 'dbt_valid_from']) }} as coverholder_key,
 4:     coverholder_id,
 5:     coverholder_name,
 6:     country,
 7:     approval_status,
 8:     oversight_rating,
 9:     dbt_valid_from                                   as valid_from,
10:     coalesce(dbt_valid_to, cast('9999-12-31' as timestamp)) as valid_to,
11:     dbt_valid_to is null                             as is_current
12: from {{ ref('coverholder_snapshot') }}

Replacing a null valid_to with a far-future date makes range joins from the facts simpler.

Joining facts to the right version

1: select
2:     r.*,
3:     c.coverholder_key
4: from {{ ref('stg_risks') }} r
5: join {{ ref('dim_coverholder') }} c
6:   on  c.coverholder_id = r.coverholder_id
7:   and r.risk_inception_date >= c.valid_from
8:   and r.risk_inception_date <  c.valid_to

Now "premium written while the coverholder was suspended" is a simple filter on approval_status, using the version that applied at the time.

Things to watch

  • Run snapshots on a schedule. A snapshot only sees the state of the source when it runs. Changes made and reverted between two runs are never captured. For reference data that changes rarely, daily is usually enough.
  • History starts on day one. A snapshot can't recreate the past. If you need history before that, load it separately, for example from archived extracts, into a table with the same columns.
  • Back it up. Snapshot tables hold history that can't be rebuilt from the source. Don't drop them casually in a full refresh, and make sure your platform's retention or time travel settings cover them.
  • Mind the time zone. dbt_valid_from comes from the timestamp column or the run time. Keep it consistent with the dates in your facts, or range joins will miss on boundary days.
  • Test it. A simple test that every coverholder_id has exactly one current row catches most problems early.
1: # models/marts/_marts.yml
2: models:
3:   - name: dim_coverholder
4:     tests:
5:       - dbt_utils.unique_combination_of_columns:
6:           combination_of_columns: ['coverholder_id', 'valid_from']
7:     columns:
8:       - name: coverholder_key
9:         tests: [unique, not_null]

Snapshots take away almost all of the hand-written SCD code I used to maintain. The design questions don't go away, though: which columns to track, what counts as a delete, and how facts pick the right version.

June 19, 2025

Deploying AWS Glue Jobs with the AWS CDK in Python

Creating an AWS Glue job in the console takes a couple of minutes. Creating the same job consistently in dev, staging and production, with the right IAM role, script version, worker settings, job parameters and schedule, and keeping all three in step a year later, is a different problem. Console-built jobs drift: someone changes the worker count in prod to fix an incident, and nobody remembers to change it anywhere else.

For the last few years I've defined Glue jobs and everything around them with the AWS CDK in Python. The CDK generates CloudFormation, so every environment is built from the same code, every change goes through a pull request, and the console becomes read-only in practice. This post shows the patterns I use, with an insurance data pipeline as the example.

Project layout

 1: glue-platform/
 2:   app.py
 3:   cdk.json
 4:   stacks/
 5:     glue_jobs_stack.py
 6:   glue_scripts/
 7:     load_risks.py
 8:     load_claims.py
 9:   tests/
10:     test_glue_jobs_stack.py

Environment settings in context

Settings that differ by environment live in cdk.json, not in the code:

 1: {
 2:   "app": "python app.py",
 3:   "context": {
 4:     "environments": {
 5:       "dev":     { "account": "111111111111", "region": "eu-west-2", "max_workers": 4,  "schedule": null },
 6:       "staging": { "account": "222222222222", "region": "eu-west-2", "max_workers": 10, "schedule": null },
 7:       "prod":    { "account": "333333333333", "region": "eu-west-2", "max_workers": 20, "schedule": "cron(0 5 * * ? *)" }
 8:     }
 9:   }
10: }
 1: # app.py
 2: import aws_cdk as cdk
 3: from stacks.glue_jobs_stack import GlueJobsStack
 4: 
 5: app = cdk.App()
 6: env_name = app.node.try_get_context("env") or "dev"
 7: cfg = app.node.try_get_context("environments")[env_name]
 8: 
 9: GlueJobsStack(
10:     app, f"glue-jobs-{env_name}",
11:     env_name=env_name, cfg=cfg,
12:     env=cdk.Environment(account=cfg["account"], region=cfg["region"]),
13: )
14: app.synth()

Deploying an environment is then cdk deploy -c env=staging.

The stack: buckets, role, scripts and jobs

 1: # stacks/glue_jobs_stack.py
 2: from aws_cdk import Stack, RemovalPolicy, aws_s3 as s3, aws_iam as iam, aws_glue as glue
 3: from aws_cdk.aws_s3_assets import Asset
 4: from constructs import Construct
 5: 
 6: class GlueJobsStack(Stack):
 7:     def __init__(self, scope: Construct, cid: str, *, env_name: str, cfg: dict, **kwargs):
 8:         super().__init__(scope, cid, **kwargs)
 9: 
10:         data_bucket = s3.Bucket(
11:             self, "DataBucket",
12:             bucket_name=f"data-{env_name}-{self.account}",
13:             encryption=s3.BucketEncryption.S3_MANAGED,
14:             block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
15:             enforce_ssl=True,
16:             removal_policy=RemovalPolicy.RETAIN,
17:         )
18: 
19:         role = iam.Role(
20:             self, "GlueJobRole",
21:             assumed_by=iam.ServicePrincipal("glue.amazonaws.com"),
22:             managed_policies=[iam.ManagedPolicy.from_aws_managed_policy_name(
23:                 "service-role/AWSGlueServiceRole")],
24:         )
25:         data_bucket.grant_read_write(role)
26: 
27:         for job_name in ["load_risks", "load_claims"]:
28:             self._glue_job(job_name, role, data_bucket, env_name, cfg)

Two details matter here. RemovalPolicy.RETAIN stops a stack deletion from deleting the data, and grant_read_write creates a least-privilege policy for that one bucket instead of a hand-written wildcard.

A reusable job definition

The scripts are uploaded as CDK assets, so every deployment ships the script version that's in the same commit as the job definition. That rules out the classic mismatch where the job definition changed but someone forgot to upload the new script, or the other way round.

 1:     def _glue_job(self, job_name, role, data_bucket, env_name, cfg):
 2:         script = Asset(self, f"{job_name}Script", path=f"glue_scripts/{job_name}.py")
 3:         script.grant_read(role)
 4: 
 5:         glue.CfnJob(
 6:             self, f"{job_name}Job",
 7:             name=f"{job_name}_{env_name}",
 8:             role=role.role_arn,
 9:             glue_version="5.0",
10:             worker_type="G.1X",
11:             number_of_workers=cfg["max_workers"],
12:             timeout=120,
13:             max_retries=1,
14:             command=glue.CfnJob.JobCommandProperty(
15:                 name="glueetl",
16:                 python_version="3",
17:                 script_location=script.s3_object_url,
18:             ),
19:             default_arguments={
20:                 "--enable-auto-scaling": "true",
21:                 "--enable-metrics": "true",
22:                 "--enable-continuous-cloudwatch-log": "true",
23:                 "--job-bookmark-option": "job-bookmark-disable",
24:                 "--datalake-formats": "iceberg",
25:                 "--data_bucket": data_bucket.bucket_name,
26:                 "--env_name": env_name,
27:             },
28:             tags={"project": "data-platform", "env": env_name},
29:         )

I use the L1 CfnJob construct because it maps one-to-one to CloudFormation and is stable. There's a higher-level Glue construct library too, which is worth a look if you want friendlier defaults.

Job parameters such as --data_bucket and --env_name mean the script never hard-codes an environment. Inside the script they're read with getResolvedOptions.

Orchestration with Step Functions

Risk transactions must load before claims, because claims reference risks. A small Step Functions state machine runs the jobs in order and waits for each to finish:

 1: from aws_cdk import aws_stepfunctions as sfn, aws_stepfunctions_tasks as tasks
 2: from aws_cdk import aws_events as events, aws_events_targets as targets
 3: 
 4: risk = tasks.GlueStartJobRun(
 5:     self, "LoadRisk", glue_job_name=f"load_risk_transactions_{env_name}",
 6:     integration_pattern=sfn.IntegrationPattern.RUN_JOB)
 7: 
 8: claims = tasks.GlueStartJobRun(
 9:     self, "LoadClaims", glue_job_name=f"load_claim_transactions_{env_name}",
10:     integration_pattern=sfn.IntegrationPattern.RUN_JOB)
11: 
12: machine = sfn.StateMachine(
13:     self, "DailyLoad",
14:     definition_body=sfn.DefinitionBody.from_chainable(risk.next(claims)))
15: 
16: if cfg["schedule"]:
17:     events.Rule(self, "DailySchedule",
18:                 schedule=events.Schedule.expression(cfg["schedule"]),
19:                 targets=[targets.SfnStateMachine(machine)])

The schedule only exists in production, because the context sets it to null elsewhere. Dev and staging runs are started by hand or from CI. Add a failure branch that publishes to an SNS topic and you have alerting too.

Testing the stack

CDK's assertions module lets you test the generated template, which catches mistakes before they reach AWS:

 1: # tests/test_glue_jobs_stack.py
 2: import aws_cdk as cdk
 3: from aws_cdk.assertions import Template, Match
 4: from stacks.glue_jobs_stack import GlueJobsStack
 5: 
 6: def test_jobs_use_glue_5_and_auto_scaling():
 7:     app = cdk.App()
 8:     cfg = {"account": "111111111111", "region": "eu-west-2", "max_workers": 4, "schedule": None}
 9:     stack = GlueJobsStack(app, "test", env_name="dev", cfg=cfg,
10:                           env=cdk.Environment(account=cfg["account"], region=cfg["region"]))
11:     template = Template.from_stack(stack)
12: 
13:     template.resource_count_is("AWS::Glue::Job", 2)
14:     template.has_resource_properties("AWS::Glue::Job", {
15:         "GlueVersion": "5.0",
16:         "DefaultArguments": Match.object_like({"--enable-auto-scaling": "true"}),
17:     })

Deploying from GitHub Actions

The pipeline runs the tests, shows a cdk diff on pull requests, and deploys on merge. It authenticates to AWS with OpenID Connect, so there are no long-lived access keys stored in GitHub:

 1: name: deploy
 2: on:
 3:   push:
 4:     branches: [main]
 5: permissions:
 6:   id-token: write
 7:   contents: read
 8: jobs:
 9:   deploy-staging:
10:     runs-on: ubuntu-latest
11:     steps:
12:       - uses: actions/checkout@v4
13:       - uses: actions/setup-python@v5
14:         with: { python-version: '3.11' }
15:       - uses: actions/setup-node@v4
16:         with: { node-version: '20' }
17:       - run: npm install -g aws-cdk && pip install -r requirements.txt
18:       - run: pytest -q
19:       - uses: aws-actions/configure-aws-credentials@v4
20:         with:
21:           role-to-assume: arn:aws:iam::222222222222:role/github-deploy
22:           aws-region: eu-west-2
23:       - run: cdk deploy -c env=staging --require-approval never

Production uses the same workflow behind a GitHub environment with required reviewers, so a person approves each production release.

What I've learned

  • Treat the console as read-only. Any manual change will be overwritten by the next deployment, which is exactly the point.
  • Keep environment differences in context, not in if env == "prod" branches scattered through the code.
  • Ship scripts as assets so the job definition and the script can never get out of step.
  • Retain data buckets and anything else you can't afford to lose if a stack is deleted.
  • Run cdk diff in every pull request. Reviewers see exactly what will change in AWS, not just the code.

April 24, 2025

dbt Incremental Models: Handling Late and Corrected Insurance Data

Rebuilding a table from scratch on every run is the simplest and safest thing dbt can do. It's also the most expensive. Once a premium or claims transaction table reaches tens of millions of rows across many years of account, a full rebuild every day wastes compute on history that hasn't changed.

Incremental models fix that: on each run, dbt processes only new or changed rows and merges them into the existing table. They're also where most dbt mistakes happen, especially with insurance data, where corrections and late transactions are normal. This post covers how they work and the patterns I use to keep them correct.

A basic incremental model

 1: -- models/marts/fct_claims.sql
 2: {{
 3:   config(
 4:     materialized = 'incremental',
 5:     unique_key   = ['claim_ref', 'bordereau_month'],
 6:     incremental_strategy = 'merge'
 7:   )
 8: }}
 9: 
10: select
11:     claim_ref,
12:     umr,
13:     section_no,
14:     bordereau_month,
15:     claim_status,
16:     paid_this_month,
17:     outstanding_reserve,
18:     fees_paid,
19:     original_ccy,
20:     loaded_at
21: from {{ ref('stg_claims') }}
22: 
23: {% if is_incremental() %}
24:   where loaded_at > (select max(loaded_at) from {{ this }})
25: {% endif %}

Three pieces make it work:

  • is_incremental() is true when the table already exists and you're not running a full refresh. On the first run, the filter is skipped and everything loads.
  • {{ this }} refers to the existing target table, so the model can find its own high-water mark.
  • unique_key tells dbt how to match incoming rows to existing ones. With the merge strategy, matches are updated and new keys are inserted.

Choosing a strategy

StrategyWhat happensUse it when
appendNew rows are inserted, nothing is updatedTruly append-only data, such as an audit log
mergeMERGE on unique_keyRows can be corrected later. The usual choice.
insert_overwriteReplaces whole partitionsData is reloaded a period at a time
replace_where (Databricks)Replaces rows matching a predicateReplacing a bordereau month in one go

Adapters differ in which strategies they support and what the default is, so check yours. On Snowflake and Databricks, merge is the common choice for transaction tables.

The late-data problem

The filter loaded_at > max(loaded_at) assumes rows always arrive in order. In insurance they often don't:

  • A corrected bordereau for March arrives in May.
  • The feed is reprocessed upstream and old rows come back with older load timestamps.
  • A transaction's business date is months before the date it was received.

A strict high-water mark can miss these rows forever. The fix is a lookback window: reprocess a few days or weeks before the high-water mark on every run, and let the MERGE deal with rows that haven't actually changed.

1: {% if is_incremental() %}
2:   where loaded_at >= (
3:       select dateadd(day, -{{ var('lookback_days', 7) }}, max(loaded_at))
4:       from {{ this }}
5:   )
6: {% endif %}

The lookback costs a little extra compute and buys a lot of safety. Adjust it per model through a variable, for example dbt build --vars '{lookback_days: 45}' after a known upstream reload. (Date functions differ between warehouses. dateadd works on Snowflake and Databricks SQL. Check yours.)

Deduplicate before merging

If the incoming batch has two versions of the same key, a MERGE either fails ("multiple source rows matched") or picks one at random, depending on the platform. Always reduce the batch to one row per key, keeping the latest:

 1: with source as (
 2:     select * from {{ ref('stg_claims') }}
 3:     {% if is_incremental() %}
 4:       where loaded_at >= (select dateadd(day, -7, max(loaded_at)) from {{ this }})
 5:     {% endif %}
 6: ),
 7: latest as (
 8:     select *
 9:     from source
10:     qualify row_number() over (
11:         partition by claim_ref, bordereau_month
12:         order by loaded_at desc
13:     ) = 1
14: )
15: select * from latest

Only update what changed

With the lookback, most incoming rows are identical to what's already there. Updating them anyway rewrites files for nothing. On adapters that support it, merge_update_columns limits the update to the columns that can actually change:

1: {{
2:   config(
3:     materialized = 'incremental',
4:     unique_key   = ['claim_ref', 'bordereau_month'],
5:     incremental_strategy = 'merge',
6:     merge_update_columns = ['claim_status', 'paid_this_month', 'outstanding_reserve', 'fees_paid', 'loaded_at']
7:   )
8: }}

Schema changes

When you add a column to an incremental model, the existing table doesn't have it. on_schema_change controls what happens:

1: {{ config(materialized='incremental', unique_key='claim_ref', on_schema_change='append_new_columns') }}

append_new_columns adds new columns to the table but leaves existing rows null for them. If the new column needs to be populated for history, plan a full refresh.

Full refreshes

1: dbt build --select fct_claims --full-refresh

A full refresh rebuilds the table from scratch. You'll need it after logic changes that affect history, such as a new currency conversion rule or a corrected commission calculation. Two tips:

  • For very large tables, protect them from accidental full refreshes with full_refresh = false in the config, and remove it deliberately when needed.
  • Make sure the model gives the same result whether it's run incrementally or from scratch. A periodic comparison of totals by year of account, between an incremental table and a full rebuild in dev, is a good way to catch logic that only works one way.

Checklist

  • Use merge with a real business key, not a surrogate.
  • Add a lookback window. Insurance data is rarely on time.
  • Deduplicate the batch to one row per key.
  • Limit updates to columns that change.
  • Decide on_schema_change deliberately.
  • Test that incremental and full-refresh results match.

February 13, 2025

dbt for SQL Server Developers: Models, Sources and Tests

For most of my career, transformation logic lived in stored procedures and SSIS packages. Dependencies were in someone's head or a scheduling spreadsheet, tests were manual row counts, and documentation was a Word document that was out of date the week it was written. I've started using dbt recently, and it fixes most of that without asking you to learn a new language. It's still SQL. It just adds the engineering practices around it.

This post introduces dbt from a SQL Server developer's point of view, using an insurance example: building premium reporting tables from a bordereaux feed. The examples use the dbt-databricks adapter, but almost everything is the same on Snowflake or any other warehouse.

What dbt is (and isn't)

  • dbt doesn't move data. It runs SQL inside your warehouse or lakehouse, so the data must already be loaded.
  • Each model is a SELECT statement in a .sql file. dbt wraps it in the right CREATE TABLE AS, CREATE VIEW or MERGE.
  • Models reference each other with ref(), and dbt builds the dependency graph from those references. No more hand-maintained run order.
  • Tests and documentation live next to the SQL, in YAML files, and are version-controlled with it.

Setting up

1: pip install dbt-databricks
2: dbt init analytics

Connection details go in ~/.dbt/profiles.yml, outside the project, so credentials never end up in Git:

 1: analytics:
 2:   target: dev
 3:   outputs:
 4:     dev:
 5:       type: databricks
 6:       host: adb-1234567890123456.7.azuredatabricks.net
 7:       http_path: /sql/1.0/warehouses/abcdef1234567890
 8:       catalog: dev
 9:       schema: dbt_dev
10:       token: "{{ env_var('DATABRICKS_TOKEN') }}"
11:       threads: 4

Project structure

I keep a simple three-folder layout:

1: models/
2:   staging/        -- one model per source table: rename, cast, light cleaning
3:   intermediate/   -- joins and business logic
4:   marts/          -- facts and dimensions for reporting

Sources

Raw tables that dbt doesn't build are declared as sources. That gives you one place to change if a table moves, plus freshness checks:

 1: # models/staging/_sources.yml
 2: version: 2
 3: 
 4: sources:
 5:   - name: feed
 6:     database: prod
 7:     schema: raw
 8:     tables:
 9:       - name: premium
10:         loaded_at_field: loaded_at
11:         freshness:
12:           warn_after: {count: 2, period: day}
13:           error_after: {count: 5, period: day}
14:       - name: contract_section
15:       - name: coverholder
16:       - name: broker

A staging model

Staging models do one job: make the source usable. Rename columns to a standard, cast types, and nothing else.

 1: -- models/staging/stg_premium.sql
 2: select
 3:     umr,
 4:     section_no,
 5:     certificate_ref,
 6:     upper(trim(transaction_type))           as transaction_type,
 7:     cast(bordereau_month as date)           as bordereau_month,
 8:     original_ccy,
 9:     cast(gross_premium  as decimal(18,2))   as gross_premium,
10:     cast(commission_pct as decimal(9,4))    as commission_pct,
11:     cast(brokerage_pct  as decimal(9,4))    as brokerage_pct,
12:     loaded_at
13: from {{ source('feed', 'premium') }}

A mart model

 1: -- models/marts/fct_premium.sql
 2: {{ config(materialized='table') }}
 3: 
 4: with premium as (
 5:     select * from {{ ref('stg_premium') }}
 6: ),
 7: sections as (
 8:     select * from {{ ref('dim_section') }}
 9: ),
10: roe as (
11:     select * from {{ ref('stg_fx_rates') }}
12: )
13: 
14: select
15:     s.contract_section_key,
16:     s.coverholder_key,
17:     s.broker_key,
18:     p.certificate_ref,
19:     p.transaction_type,
20:     p.bordereau_month,
21:     p.original_ccy,
22:     p.gross_premium,
23:     p.gross_premium * r.rate_to_gbp                              as gross_premium_gbp,
24:     p.gross_premium * p.commission_pct / 100 * r.rate_to_gbp     as commission_gbp,
25:     p.gross_premium * p.brokerage_pct  / 100 * r.rate_to_gbp     as brokerage_gbp
26: from premium p
27: join sections s
28:   on  s.umr = p.umr
29:   and s.section_no = p.section_no
30: left join roe r
31:   on  r.currency = p.original_ccy
32:   and r.roe_month = p.bordereau_month

Because this model uses ref('dim_section') and ref('stg_premium'), dbt knows to build those first. Run dbt docs generate and you get a browsable lineage graph of the whole project.

Materialisations

MaterialisationWhat dbt createsGood for
viewA viewStaging models, light logic
tableA table, rebuilt every runDimensions, smaller facts
incrementalA table that only processes new or changed rowsLarge transaction facts
ephemeralNothing. It's inlined as a CTESmall reusable pieces of logic

Set defaults per folder in dbt_project.yml so individual models rarely need a config block:

1: models:
2:   analytics:
3:     staging:
4:       +materialized: view
5:       +schema: staging
6:     marts:
7:       +materialized: table
8:       +schema: reporting

Tests from day one

 1: # models/marts/_marts.yml
 2: version: 2
 3: 
 4: models:
 5:   - name: fct_premium
 6:     columns:
 7:       - name: contract_section_key
 8:         tests:
 9:           - not_null
10:           - relationships:
11:               to: ref('dim_section')
12:               field: contract_section_key
13:       - name: transaction_type
14:         tests:
15:           - accepted_values:
16:               values: ['NEW', 'RENEWAL', 'MTA', 'CANCELLATION']

The relationships test is the one I'd miss most. It catches premium rows whose contract section doesn't exist in the dimension, which in a stored procedure would quietly disappear in an inner join.

Running it

1: dbt build
2: dbt build --select fct_premium+
3: dbt source freshness

dbt build runs each model and then its tests before moving on. If a test fails, models downstream of it are skipped, so bad data doesn't flow into reports.

What changes for a SQL Server developer

  • Write SELECTs, not DDL. dbt handles CREATE, DROP and swaps.
  • Use ref() and source(), never hard-coded table names. That's what makes environments, lineage and run order work.
  • Small models beat big procedures. A 600-line stored procedure becomes five or six models, each easy to test and understand.
  • Everything is in Git. Code reviews for SQL become normal.

Next I'll look at incremental models, which is where dbt starts to matter for large transaction tables.