Find the First Ledger Entry That Drove a Balance Negative
Last updated: November 29, 2026
Quick Overview
Given a ledger_entries table of signed amounts per user and asset, compute running balances and return, for each user and asset, the first entry after which the balance went below zero.
Coinbase
November 29, 20260
0
0 solved
Given a ledger_entries table of signed amounts per user and asset, compute running balances and return, for each user and asset, the first entry after which the balance went below zero.
Coinbase data engineers build reconciliation checks over the ledger, and a negative customer balance signals a bug, a race or fraud that needs immediate investigation. The interviewer checks window function fluency, a deterministic ordering and the trap of filtering before computing running sums.
What the Interviewer Expects
- Use SUM() OVER with PARTITION BY user and asset
- Order by timestamp plus a unique tiebreaker
- Compute the running total before filtering to negative rows
- Pick the first negative row with ROW_NUMBER
- Explain how to validate against a known example
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you run this incrementally each hour over billions of rows?
- How would you also report how long the balance stayed negative?
- What if amounts are stored as strings with 18 decimals?
- How would you exclude pending holds that later reversed?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
ledger_entries(entry_id, user_id, asset, created_at, amount) where amount is a signed integer in base units. Entries can share a timestamp, so entry_id (monotonic) is the tiebreaker. Balances star...
Approach
First compute the running balance over every entry, partitioned by user and asset and ordered by (created_at, entry_id) with an explicit ROWS frame. Only after that filter to rows with a negative ru...