Skip to content

9. Data Test: Refunds Larger Than the Order

Difficulty: Easy · Topic: Data tests

A singular data test in dbt is a SELECT in tests/ that returns the rows that break a rule; the test passes when it returns nothing.

Write assert_refunds_within_order_amount: an order can be refunded in several parts, but the total refunded must never exceed the order's amount. Return one row per violating order with order_id, order_amount and refunded_amount (the total refunded).

Refunding exactly the order amount is allowed.

Your model is compiled like dbt does and run in DuckDB against 3 test cases, including hidden edge cases.

Sample inputs

{{ ref('stg_orders') }}

order_idcustomer_idordered_onstatusamount
1102024-01-01completed50
2112024-01-02completed20
3122024-01-03completed30

{{ ref('stg_refunds') }}

refund_idorder_idrefunded_atamount
90012024-01-0530
90112024-01-0625
90222024-01-075
90332024-01-0830

Expected output

order_idorder_amountrefunded_amount
15055

Hints

Hint 1Sum refunds per order first, then compare that total with the order amount.
Hint 2Comparing each refund with the order amount misses orders refunded in several small parts.
Hint 3Only orders that have refunds can fail, so an inner join between orders and the refund totals is fine here.

More dbt problems

All dbt problems