14. Test the Grain of a Daily Fact Table
Difficulty: Medium · Topic: Data tests
fct_store_sales (store_id, sale_date, orders, revenue) should have one row per store per day. Write models/schema.yml tests for its rules:
- One row per
store_idandsale_date, neither ever missing. ordersandrevenueare never negative.- A day with no orders has no revenue.
Clean datasets must pass every test; broken ones must make at least one test fail. dbt_utils is installed (unique_combination_of_columns, expression_is_true, accepted_range).
Your schema.yml tests run on 7 datasets, including hidden ones: clean datasets must pass every test, broken ones must make a test fail.
Clean data (clean)
{{ ref('fct_store_sales') }}
| store_id | sale_date | orders | revenue |
|---|---|---|---|
| 1 | 2024-03-01 | 12 | 340 |
| 1 | 2024-03-02 | 9 | 210.5 |
| 2 | 2024-03-01 | 0 | 0 |
| 2 | 2024-03-02 | 4 | 80 |
The same store-day twice (broken)
A rerun appended store 1's day again.
{{ ref('fct_store_sales') }}
| store_id | sale_date | orders | revenue |
|---|---|---|---|
| 1 | 2024-03-01 | 12 | 340 |
| 1 | 2024-03-01 | 12 | 340 |
| 2 | 2024-03-01 | 3 | 60 |
Hints
Hint 1
The grain is two columns together: a store has many days and a day has many stores, sounique on either column fails on clean data.Hint 2
Tests about several columns go under the model itself (data_tests: next to columns:): dbt_utils.unique_combination_of_columns with combination_of_columns: [store_id, sale_date].Hint 3
"No orders means no revenue" is a condition on two columns:dbt_utils.expression_is_true at model level with expression: "orders > 0 or revenue = 0".Learn the concepts
- Packages and dbt_utils · 4 min read. packages.yml, dbt deps, and the dbt_utils macros interviews expect you to know, starting with surrogate keys.