KatInterview

Payment Risk Scoring with Rolling Windows and NULL Handling in SQL

SQL & DataModel answer
MediumModel answerSQL & Datawindow-functionsaggregationcase-when

Last updated

Analyze a payments table to rank users by declined volume, flag burst activity in 24-hour windows, and classify each transaction by amount using conditional logic.

You are given a transactions table with the following schema and sample data:

transactions

+----------------+---------+--------+----------+---------------------+
| transaction_id | user_id | amount | status   | timestamp           |
+----------------+---------+--------+----------+---------------------+
| 101            | 10      | 120.50 | success  | 2023-06-01 10:00:00 |
| 102            | 10      | 250.00 | declined | 2023-06-02 12:30:00 |
| 103            | 12      | 900.00 | success  | 2023-06-01 11:15:00 |
| 104            | 10      | 80.00  | success  | 2023-06-03 09:40:00 |
| 105            | 13      | 500.00 | success  | 2023-06-02 14:55:00 |
+----------------+---------+--------+----------+---------------------+

A financial monitoring team wants you to produce three separate analyses from this table.

Part 1 — Top declined-volume users. Write a query that returns the top 3 users with the largest total amount across declined transactions within the trailing 7 days relative to CURRENT_DATE. Handle ties in total amount so that tied users are not arbitrarily cut off.

Part 2 — Rolling 24-hour burst detection. For every user and every calendar day, determine whether that user had more than two transactions satisfying amount IS NULL OR amount > 500 inside some 24-hour rolling window. Output user_id, window_start (the timestamp at which the densest such window begins), and risky_flag (1 if the threshold was exceeded, 0 otherwise). Days with no qualifying transactions should still appear with risky_flag = 0.

Part 3 — Amount-based risk classification. Add a derived column risk_level to the transactions table using CASE WHEN: 'high' when amount > 800, 'medium' when amount is between 500 and 800 inclusive, 'low' otherwise. Return 10 rows, most recent first. Be explicit about how NULL amounts are handled.

State any assumptions you make about the meaning of "last 7 days," whether windows are inclusive or half-open, and how ties are resolved. PostgreSQL syntax is fine.

Hints

Hint 1

Consider whether 'last 7 days' means 7 calendar days including today or a 168-hour lookback from now; confirm with the interviewer.

Hint 2

Only windows anchored at an actual transaction timestamp can achieve the maximum count inside any 24-hour span, so you never need to check infinitely many windows.

Hint 3

In CASE WHEN, a NULL amount silently falls through every comparison into the ELSE branch; handle it explicitly if a distinct label is desired.

Hint 4

Use DENSE_RANK instead of LIMIT to avoid arbitrarily dropping users who tie for third place.