dbt Incremental Models and Snapshots, Hands-On

An incremental model adds only new rows on each run instead of rebuilding the table. A snapshot keeps the history of rows that change. Both are easiest to understand by running them twice. Here is the code, and where to run it free.

Open the dbt Lab

Incremental model

{{ config(materialized='incremental', unique_key='order_date') }}

select order_date, count(*) as orders, round(sum(amount), 2) as revenue
from {{ ref('orders') }}
{% if is_incremental() %}
where order_date > (select max(order_date) from {{ this }})
{% endif %}
group by order_date
  • The first run builds the table: `is_incremental()` is false.
  • Later runs only add newer days. `{{ this }}` is the existing table. `unique_key` updates a day if it comes again.
  • `dbt run --full-refresh` rebuilds it from scratch.

Snapshot (type 2 history)

{% snapshot customers_snapshot %}
{{ config(target_schema='snapshots', unique_key='customer_id', strategy='check', check_cols=['country']) }}
select * from {{ ref('stg_customers') }}
{% endsnapshot %}

dbt adds dbt_valid_from and dbt_valid_to. Change a customer's country in seeds/raw_customers.csv, run dbt seed and dbt snapshot again, and the customer gets a second row: the old one closed, the new one open.

Try it

Open the dbt Lab, go to **Going further** and run **Incremental models** and **Snapshots**. The Preview tab shows the rows after each run.

Open the dbt Lab

Also try

How to use the dbt Lab: step by step

  1. Start the dbt Lab and connect
  2. Run the Incremental models lesson twice
  3. Run the Snapshots lesson, change a seed row, run it again
  4. Preview the tables

When to use the dbt Lab

  • Large fact tables that grow every day
  • Keeping history of slowly changing dimensions
  • Interview preparation for analytics engineering