Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Table txn(id bigint, account_id int, tx_time timestamptz, amount numeric). Write a query that shows each transaction with the running balance of its account, and a second column with the sum of the last 7 days of amounts up to that row.

The running balance is SUM(amount) OVER (PARTITION BY account_id ORDER BY tx_time, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW); the id tie-breaker and the ROWS frame give each row its own balance even when two transactions share a timestamp. The 7 day sum is SUM(amount) OVER (PARTITION BY account_id ORDER BY tx_time RANGE BETWEEN INTERVAL '7 days' PRECEDING AND CURRENT ROW), which PostgreSQL 11 and later and MySQL 8 support.

Why this question is asked

Running totals are everywhere in business software: account balances, cumulative revenue, stock levels, points earned so far. Before window functions they were slow and awkward to write; with them they are one line, but that line has a frame clause that most people copy without understanding, and it decides whether ties produce correct balances. Interviewers ask this question to check exactly that. In this answer, we will recap window frames, write the running balance, see what the tie-breaker and ROWS do, write the 7 day sum with a RANGE interval frame, compare with the old correlated subquery, and answer the follow-up about month-end balances.

1A Quick Recap of Window Frames

A window function computes a value for each row from a set of related rows. PARTITION BY account_id says which rows are related: those of the same account. ORDER BY tx_time puts them in order. The frame says which of those ordered rows count for the current row, for example "all rows from the start up to this one".

There are two main frame modes. ROWS counts physical rows: "from the first row up to the current row" means exactly that. RANGE works on values of the ORDER BY column: "up to the current row" includes every row with the same ORDER BY value as the current one, called its peers, and an offset like INTERVAL '7 days' PRECEDING means "rows whose tx_time is within 7 days before this one". That difference is the key to both columns in this question.

SQL
INSERT INTO txn (id, account_id, tx_time, amount) VALUES
(1, 1, '2026-03-01 09:00', 100),
(2, 1, '2026-03-03 10:00', -30),
(3, 1, '2026-03-03 10:00', -20), -- same timestamp as id 2
(4, 1, '2026-03-12 08:00', 50);

2The Running Balance

We sum every amount from the account's first transaction up to the current one. Ordering by tx_time and then id gives a unique order, and the ROWS frame makes each row include itself and the rows before it, nothing more.

SQL
SELECT id, tx_time, amount,
SUM(amount) OVER (PARTITION BY account_id
ORDER BY tx_time, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS balance
FROM txn
ORDER BY account_id, tx_time, id;
-- 1 | 03-01 09:00 | 100 | 100
-- 2 | 03-03 10:00 | -30 | 70
-- 3 | 03-03 10:00 | -20 | 50
-- 4 | 03-12 08:00 | 50 | 100
Rows 2 and 3 share a timestamp
idamountROWS, ORDER BY tx_time, iddefault RANGE, ORDER BY tx_time
1100100100
2-307050 (includes row 3)
3-205050
450100100

Notice rows 2 and 3. They share a timestamp, yet each shows its own balance, 70 and then 50, because id breaks the tie and ROWS stops exactly at the current row. Without both, the default frame would be RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which includes all peers, and both rows would show 50. The final balance would still be right, but a statement printed from it would show a balance that never existed after transaction 2.

3The 7 Day Sum With a RANGE Interval Frame

For the second column we want the sum of the amounts whose tx_time falls in the 7 days up to the current row. That is a frame defined by values, not by a number of rows, because an account may have 2 transactions in one week and 200 in another. RANGE with an interval offset does exactly this. PostgreSQL supports it from version 11 and MySQL from 8.0.

SQL
SELECT id, tx_time, amount,
SUM(amount) OVER (PARTITION BY account_id
ORDER BY tx_time
RANGE BETWEEN INTERVAL '7 days' PRECEDING AND CURRENT ROW) AS last_7_days
FROM txn;
-- 1 | 03-01 09:00 | 100 | 100 window 02-22 09:00 .. 03-01 09:00
-- 2 | 03-03 10:00 | -30 | 50 window 02-24 10:00 .. 03-03 10:00, includes row 3 (a peer)
-- 3 | 03-03 10:00 | -20 | 50
-- 4 | 03-12 08:00 | 50 | 50 window 03-05 08:00 .. 03-12 08:00
-- MySQL 8 writes the offset as: RANGE BETWEEN INTERVAL 7 DAY PRECEDING AND CURRENT ROW

Two details matter. A RANGE frame with an offset needs exactly one ORDER BY column, of a type the interval can be subtracted from, so we cannot add id here. As a result, rows 2 and 3 are peers and both include each other, which for a "last 7 days" figure is usually what we want: both happened at the same instant. And the boundaries are inclusive, so a transaction exactly 7 days earlier counts; if the business means "strictly less than 7 days", we adjust the interval, for example to INTERVAL '7 days' - INTERVAL '1 microsecond', or agree on calendar days.

4How People Did It Before Window Functions

Before window functions, a running total was a correlated subquery: for each row, sum all earlier rows of the same account.

SQL
SELECT t1.id, t1.amount,
(SELECT SUM(t2.amount) FROM txn t2
WHERE t2.account_id = t1.account_id
AND (t2.tx_time, t2.id) <= (t1.tx_time, t1.id)) AS balance
FROM txn t1;
-- same balances: 100, 70, 50, 100
Step throughHow the window computes the balance
  1. Partition rows by account_idaccount 1 is processed alone
  2. Sort by tx_time, ida unique order, ties broken by id
  3. Add the current amount to the running sumone addition per row
  4. Emit the sum as the row's balance100, 70, 50, 100

4 steps in order. Play them, or step through them one at a time.

It gives the right answer, but for an account with n transactions it sums 1 + 2 + ... + n rows, about n x n / 2. An account with 10,000 transactions means 50 million additions. The window function reads the rows once in order and keeps a running sum, so it is linear. The correlated form is worth recognizing in old code, and replacing.

5The Follow-Up: Balance at Each Month End

For a month-end balance per account, we can aggregate per month first and then run the window over months: SUM(SUM(amount)) is a window SUM over the result of a GROUP BY SUM, which looks odd but is valid, because window functions run after grouping.

SQL
SELECT account_id,
date_trunc('month', tx_time) AS month,
SUM(SUM(amount)) OVER (PARTITION BY account_id
ORDER BY date_trunc('month', tx_time)) AS month_end_balance
FROM txn
GROUP BY account_id, date_trunc('month', tx_time);
-- 1 | 2026-03-01 | 100

Here the default RANGE frame is fine, because each month appears once per account. Months with no transactions are missing from the result; if a statement needs every month, we generate the months with generate_series, LEFT JOIN the monthly sums, and the running sum carries the balance forward.

6Follow-up questions

How would you compute the balance only at month end for each account?

Group by account and month to get each month's net amount, then run SUM(SUM(amount)) OVER (PARTITION BY account_id ORDER BY month) to accumulate it. To include months without transactions, generate the months with generate_series and LEFT JOIN the monthly sums.

Why not use ROWS BETWEEN 6 PRECEDING for the 7 day sum?

Because ROWS counts transactions, not days. ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is the last 7 transactions, which may span an hour or a year. A time window needs RANGE with an interval.

Should the running balance be computed on every read for a large ledger?

Not from the beginning of time. For large ledgers we store periodic balance snapshots, for example closing balances per day, and add a window sum only for the rows after the latest snapshot.

7Conclusion

In this answer, we wrote the running balance as SUM(amount) OVER (PARTITION BY account_id ORDER BY tx_time, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), where the id tie-breaker and the ROWS frame give each row its own balance even when timestamps tie, unlike the default RANGE frame. The 7 day sum uses RANGE BETWEEN INTERVAL '7 days' PRECEDING AND CURRENT ROW, supported in PostgreSQL 11 and later and MySQL 8, with inclusive boundaries and peers counted together. The old correlated subquery gives the same balances at O(n^2) cost, and month-end balances come from a window sum over monthly sums.

What to say in the interviewAbout 90 seconds aloud

Open with

For the running balance I would write sum of amount over partition by account id, order by transaction time and then id, rows between unbounded preceding and current row.

Then, if they want more

Partition restarts the sum for each account, the order puts transactions in time order, and the frame says include everything from the first row up to this one.

The id tie-breaker and the ROWS frame are deliberate: if two transactions have the same timestamp, the default frame is RANGE, which includes all rows with the same ordering value, so both would show the balance after both transactions. With id and ROWS, each row shows its own balance.

For the seven day column I would use sum of amount over partition by account, order by time, range between interval seven days preceding and current row. That is a frame by value, not by row count, which is what a time window needs, because ROWS six preceding would be the last seven transactions, not seven days.

PostgreSQL supports this from version 11 and MySQL from 8. The boundaries are inclusive and same-time rows are counted together, which I would confirm with the business. Before window functions, people wrote a correlated subquery summing all earlier rows, which is quadratic per account.

For a month-end balance, I would group by month and run a window sum over the monthly sums.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8, PostgreSQL 11
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Table txn(id bigint, account_id int, tx_time timestamptz, amount numeric). Write a query...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/1fbf5e72e8/