Skip to content

18. Rerun a Day Without Duplicates

Difficulty: Medium · Topic: Incremental models

The scheduler builds fct_page_views once a day with dbt run --vars '{run_date: "2024-03-02"}', and each run loads only that day's rows from {{ source('web', 'page_views') }} (view_id, user_id, page, view_date).

Days get rerun: the scheduler retries a failed run, or the upstream team fixes a day's data (removing bot views, adding rows that arrived late) and asks you to reload it. Every rerun must leave the table as if that day had been loaded once, from the source as it is now. Other days must not change.

This problem is graded over several runs against the same table, like a real schedule: day 1, day 2, then day 2 again. The table after every run must match.

Graded over several runs against the same table, like a real schedule: 3 tests, including hidden edge cases. The table after every run must match.

Run 1 (run_date = 2024-03-01)

{{ source('web', 'page_views') }}

view_iduser_idpageview_date
110/home2024-03-01
211/pricing2024-03-01

Expected table after run 1

view_iduser_idpageview_date
110/home2024-03-01
211/pricing2024-03-01

Run 2 (run_date = 2024-03-02)

{{ source('web', 'page_views') }}

view_iduser_idpageview_date
110/home2024-03-01
211/pricing2024-03-01
310/docs2024-03-02
412/home2024-03-02
599/home2024-03-02

Expected table after run 2

view_iduser_idpageview_date
110/home2024-03-01
211/pricing2024-03-01
310/docs2024-03-02
412/home2024-03-02
599/home2024-03-02

Run 3 (run_date = 2024-03-02)

{{ source('web', 'page_views') }}

view_iduser_idpageview_date
110/home2024-03-01
211/pricing2024-03-01
310/docs2024-03-02
412/home2024-03-02
613/blog2024-03-02

Expected table after run 3

view_iduser_idpageview_date
110/home2024-03-01
211/pricing2024-03-01
310/docs2024-03-02
412/home2024-03-02
613/blog2024-03-02

Hints

Hint 1A plain incremental model appends: rerunning a day inserts its rows a second time. You need a unique_key so dbt removes rows before inserting.
Hint 2Think about what one run replaces. If the key is view_id, a row the upstream team deleted is never removed from your table.
Hint 3With delete+insert (dbt-duckdb's default) and unique_key='view_date', dbt deletes every row of the dates in the new batch, then inserts the batch: the whole day is replaced.

Learn the concepts

More dbt problems

All dbt problems