Deep Pockets

A medium SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
medium
Seniority
L3
Asked in
Amazon

Problem

We're closing the books for March 2026 and need a spend breakdown by customer. Total each customer's transactions for the month.

One month, every customer, every dollar accounted for.

Tables

transactions

Columns: transaction_id INTEGER, user_id INTEGER, product_id INTEGER, quantity INTEGER, total_amount REAL, transaction_date TEXT

transactions: 10 of 200 rows
transaction_iduser_idproduct_idquantitytotal_amounttransaction_date
10671971001223.462026-02-02
11342941050336.932026-03-03
12013911099450.42026-04-04
12684881148563.872026-05-05
13355851197002026-06-06
14026821246290.812026-07-07
146977912953104.282026-08-08
153687613444117.752026-09-09
160397313935-452026-01-10
1670107014421144.692026-02-11

Expected output

First 5 of 6 rows
user_idtotal_revenue
1001434.33
2941929.24
5851164.9299999999998
8761649.85
1167922.4699999999999

Worked solution and explanation

What this problem is really testing

This is a plain per-customer sum wearing a finance costume. The whole game is the date boundary. Anyone can write GROUP BY user_id with SUM(total_amount); what separates people is expressing 'March' as a half-open range instead of reaching for BETWEEN or LIKE, and NOT bolting on a redundant filter for 'users with at least one transaction' when the grouping already guarantees that. Botch the boundary and you either swallow April 1 or drop the last day of March, and finance reconciles against a total that is quietly wrong.


Break down the requirements

Step 1: Filter to March of the target year

Use WHERE transaction_date >= '2026-03-01' AND transaction_date < '2026-04-01'. The half-open range captures every March date, including the 31st, and cleanly excludes April even if a time component sneaks in later.

Step 2: Aggregate per customer

GROUP BY user_id with SUM(total_amount) gives each customer's March spend. Because you are grouping the transactions themselves, only customers who actually transacted in March appear. The 'at least one transaction' requirement is satisfied for free, so an extra HAVING or existence check is wasted work.

Step 3: Sort highest to lowest

ORDER BY total_revenue DESC puts the biggest spenders at the top, which is what finance reads first.


The solution

Date-range filter with per-customer aggregation
SELECT user_id, SUM(total_amount) AS total_revenue
FROM transactions
WHERE transaction_date >= '2026-03-01'
  AND transaction_date < '2026-04-01'
GROUP BY user_id

Common follow-up questions