Interview Questions/SQL/Recursive Running Balance Per Account

Recursive Running Balance Per Account

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a Transactions table. Write a SQL query to compute the running balance for each account, in chronological order of transaction date (ties broken by txn_id). Each row should show the account, date, the transaction amount, and the cumulative running balance up to and including that transaction. Return (account_id, txn_date, amount, running_balance) ordered by account_id, then txn_date, then txn_id. IMPORTANT: Use a recursive CTE (not a window function SUM OVER) to compute the running balance. Table: Transactions

Column NameTypeDescription
txn_idINTPrimary key
account_idINTAccount identifier
amountINTPositive = credit, Negative = debit
txn_dateDATETransaction date

Database Schema (Inferred)

Transactions

Column NameExample Value
txn_id1
account_id101
amount5000
txn_date2024-01-01

Example

Transactions

txn_idaccount_idamounttxn_date
110150002024-01-01
2101-15002024-01-05
310120002024-01-10
4101-5002024-01-15
510230002024-01-02
6102-10002024-01-08

Output

account_idtxn_dateamountrunning_balance
1012024-01-0150005000
1012024-01-05-15003500
1012024-01-1020005500
1012024-01-15-5005000
1022024-01-0230003000
1022024-01-08-10002000

Explanation:

Assign row numbers per account ordered by date/txn_id. Anchor at rn=1, recursively join next row (rn+1) and accumulate. Each recursive step adds current amount to parent's running_balance.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Transactions

txn_idaccount_idamounttxn_date
110150002024-01-01
2101-15002024-01-05
310120002024-01-10
4101-5002024-01-15
510230002024-01-02
6102-10002024-01-08

Output

account_idtxn_dateamountrunning_balance
1012024-01-0150005000
1012024-01-05-15003500
1012024-01-1020005500
1012024-01-15-5005000
1022024-01-0230003000
1022024-01-08-10002000