D8LooPFocus modeCODE WORKSPACE
Write a query that returns one row per detected order anomaly across duplicate orders, suspicious revenue, and invalid order-state transitions.
Break each anomaly type into a named CTE, then union the findings into a stable two-column audit result.
Sample input
| order_id | customer_id | status | gross_revenue | refund_amount |
|---|---|---|---|---|
| 1001 | 10 | placed | 120 | 0 |
| 1001 | 10 | placed | 120 | 0 |
| 1002 | 11 | paid | -25 | 0 |
| 1003 | 12 | refunded | 80 | 90 |
| order_id | event_ts | event_name |
|---|---|---|
| 1004 | 2026-03-01T12:55:00Z | cancelled |
| 1004 | 2026-03-01T12:57:00Z | paid |
| 1005 | 2026-03-01T13:30:00Z | placed |
| 1005 | 2026-03-01T13:31:00Z | paid |
Expected output
| order_id | anomaly_type |
|---|---|
| 1001 | duplicate_order |
| 1002 | negative_or_over_refund |
| 1003 | negative_or_over_refund |
| 1004 | paid_after_cancelled |
Constraints
Treat duplicate order rows, negative gross revenue, refunds larger than gross revenue, and paid events after cancellation as audit findings.
Expected skills
CTE decomposition, row-level data quality checks, event ordering, and audit output that is easy to review.
Run the SQL query to inspect preview rows.