HardWindow Functions High Frequency
Real-Time Account Ledger Running Balance
Frequently Asked By:StripeCoinbaseBloomberg
Interactive In-Browser Workspace
Practice this problem on live schema tables in PostgreSQL 16 WASM with instant row verification and visual EXPLAIN plans.
Problem Statement
For each transaction in `account_ledger_lines`, compute the real-time running balance for that specific account.
Return:
1. `line_id`
2. `account_id`
3. `amount`
4. `running_balance`: Cumulative sum of `amount` partitioned by `account_id` ordered by `line_id ASC`
Order results by `account_id` ascending, then by `line_id` ascending.
Why Technical Interviewers Ask This
Core banking ledgers process deposits (positive credits) and debits (negative withdrawals). Financial auditors require computing the exact balance of each bank account after every transaction.
Common Pitfalls & Interview Traps
Forgetting required sorting and deterministic tie-breaking.
Not accounting for NULL or zero-value denominators during calculations.
Using inefficient quadratic subqueries instead of single-pass window functions constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLSELECT
line_id,
account_id,
amount,
SUM(amount) OVER (PARTITION BY account_id ORDER BY line_id ASC) AS running_balance
FROM account_ledger_lines
ORDER BY account_id ASC, line_id ASC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Window Functions. It meets the target criteria: Ledger lines showing running balance per account.Edge Cases to Verbally Clarify with Your Interviewer
The dataset contains zero matching records (must return valid empty result without crashing).
Multiple records tie on sorting criteria (must evaluate tie-breaking order deterministically).
Foreign keys or secondary attributes have NULL values.
Frequently Asked Follow-Up Questions
What makes this question a favorite among Stripe and Coinbase interviewers?
Interviewers use this problem to test whether candidates write defensive, scalable Window Functions queries that run efficiently on multi-million row production databases without excessive memory usage.
How does the query optimizer execute this query?
Using single-pass table scans with index lookups or sort buffers. Running EXPLAIN (ANALYZE, BUFFERS) in the DB Exercises workbench visualizes the execution nodes and buffer hit cache.