Payment Risk Scoring with Rolling Windows and NULL Handling in SQL
SQL & DataModel answerLast 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
This problem tests three distinct SQL skills: filtered aggregation with ranking, rolling time-window counting with window functions, and NULL-aware conditional logic. Walking through each part and stating assumptions matters as much as the syntax itself.
Part 1 — Top declined-volume users
Filter rows to status = 'declined' within the date window, sum amounts per user, then rank. Two interpretation choices to flag:
- "Last 7 days" could mean 7 calendar days including today (
CURRENT_DATE - INTERVAL '6 days'through end of today) or a strict 168-hour lookback. UsingCURRENT_DATE - INTERVAL '7 days'anchored at midnight seven days ago, combined withtimestamp < CURRENT_DATE + INTERVAL '1 day'to exclude future rows, is a reasonable default. Confirm the intent. LIMIT 3silently drops users tied for third place.DENSE_RANK()preserves all tied users, which is usually what a risk team wants.
WITH declined AS (
SELECT user_id,
SUM(amount) AS total_declined
FROM transactions
WHERE LOWER(TRIM(status)) = 'declined'
AND timestamp >= CURRENT_DATE - INTERVAL '7 days'
AND timestamp < CURRENT_DATE + INTERVAL '1 day'
GROUP BY user_id
HAVING SUM(amount) IS NOT NULL
),
ranked AS (
SELECT user_id,
total_declined,
DENSE_RANK() OVER (ORDER BY total_declined DESC) AS rnk
FROM declined
)
SELECT user_id, total_declined
FROM ranked
WHERE rnk <= 3
ORDER BY rnk;
HAVING SUM(amount) IS NOT NULL excludes users whose declined transactions all have NULL amounts (SUM ignores NULLs, so an all-NULL group yields NULL). LOWER(TRIM(status)) guards against whitespace or casing inconsistency in the status column.
Part 2 — Rolling 24-hour burst detection
The key insight: any 24-hour window that contains k qualifying transactions can be slid forward until its start aligns with the first transaction inside it, and the window still contains all k transactions. So the maximum over all possible windows equals the maximum over windows anchored at transaction timestamps. This reduces an infinite search space to n checks per user.
A transaction is "qualifying" if amount IS NULL OR amount > 500. Note that NULL > 500 evaluates to UNKNOWN in SQL, which is falsy, so the explicit IS NULL check is required.
WITH risky AS (
SELECT user_id, timestamp
FROM transactions
WHERE amount IS NULL OR amount > 500
),
win AS (
SELECT user_id,
timestamp AS window_start,
COUNT(*) OVER (
PARTITION BY user_id
ORDER BY timestamp
RANGE BETWEEN CURRENT ROW AND INTERVAL '24 hours' FOLLOWING
) AS cnt
FROM risky
),
user_days AS (
SELECT DISTINCT user_id, CAST(timestamp AS DATE) AS day
FROM transactions
)
SELECT d.user_id,
COALESCE(
MIN(w.window_start) FILTER (WHERE w.cnt > 2),
CAST(d.day AS timestamp)
) AS window_start,
CASE WHEN MAX(w.cnt) > 2 THEN 1 ELSE 0 END AS risky_flag
FROM user_days d
LEFT JOIN win w
ON w.user_id = d.user_id
AND CAST(w.window_start AS DATE) = d.day
GROUP BY d.user_id, d.day
ORDER BY d.user_id, d.day;
The LEFT JOIN from user_days ensures clean days still appear. When no risky transactions fall on a day, the join produces NULLs: MAX(cnt) is NULL, NULL > 2 is UNKNOWN, and the CASE returns 0.
The RANGE frame is inclusive at both ends: a transaction exactly 24 hours later is counted. For a half-open [t, t+24h) window, use INTERVAL '23:59:59.999999' instead. Rows with identical timestamps are peers under RANGE, so all are included in the count.
Part 3 — Amount-based risk classification
Order CASE branches from most specific to least, and handle NULL explicitly. Without an explicit NULL branch, a NULL amount fails every comparison and silently falls into ELSE 'low', which is misleading.
SELECT transaction_id,
user_id,
amount,
status,
timestamp,
CASE
WHEN amount IS NULL THEN 'unknown'
WHEN amount > 800 THEN 'high'
WHEN amount >= 500 THEN 'medium'
ELSE 'low'
END AS risk_level
FROM transactions
ORDER BY timestamp DESC, transaction_id DESC
LIMIT 10;
The >= 500 branch covers BETWEEN 500 AND 800 because the > 800 branch already intercepted larger values. The tie-breaker on transaction_id DESC ensures deterministic ordering when timestamps collide.
Sample-data results (assuming CURRENT_DATE = 2023-06-08):
- Part 1: user 10 with 250.00.
- Part 2: no one flagged — only transaction 103 (amount 900) is risky, and one transaction does not exceed the threshold of two.
- Part 3: transaction 103 gets
high, transaction 105 getsmedium(500 is inclusive), the rest getlow.
Complexity
- Part 1: one filtered scan with a hash aggregate, O(n) time, then a sort over u distinct users, O(u log u). Space: O(u).
- Part 2: O(n log n) to sort within each user partition. The
RANGEframe evaluation is roughly linear after sorting because the frame slides forward monotonically. Space: O(n) for the window CTE. - Part 3: a single sequential scan with an in-line
CASE, O(n). Space: O(1) beyond the output.
Common mistakes
- Using
LIMIT 3in Part 1 and silently dropping tied users. - Forgetting the explicit
IS NULLcheck in Part 2, causing NULL-amount transactions to be missed. - Letting NULL amounts fall through to
'low'in Part 3 instead of labeling them distinctly. - Using
ROWSinstead ofRANGEfor the 24-hour window, which counts physical rows rather than time-based boundaries.