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.
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.
Also try
How to use the dbt Lab: step by step
- Start the dbt Lab and connect
- Run the Incremental models lesson twice
- Run the Snapshots lesson, change a seed row, run it again
- 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