Interview Q&A / SQL & DBMS

IntermediateQuick answerCoding1 min readUpdated 3 Oct 2026

Write a query to calculate a running total of daily sales.

SHORT ANSWER

Use SUM(amount) OVER (ORDER BY day) to get a cumulative sum. Add PARTITION BY to restart the total per group, and use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW to be explicit.

Explain it simply

A running total is like a passbook balance: each line shows the sum of everything up to that line. In SQL, you ask for a sum over the rows from the start up to the current row.

Line by line

Table sales(day, amount).

dayamount
2026-01-01100
2026-01-0250
2026-01-0370
sql
SELECT day, amount,
       SUM(amount) OVER (
         ORDER BY day
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS running_total
FROM sales
ORDER BY day;

Result: running_total is 100, 150, 220.

  • ORDER BY day fixes the sequence.
  • The frame UNBOUNDED PRECEDING AND CURRENT ROW means "from the first row to this one".
  • Without the explicit frame, the default is RANGE, which treats rows with equal day values as peers and gives them the same total. ROWS avoids that surprise.
  • For a total per city, write PARTITION BY city before ORDER BY.

Before window functions, this needed a self join or a correlated subquery, which is much slower.

Complexity

Time: O(n log n) for the sort, then O(n) for the pass. Space: O(n).

What to say in the interview

"SUM() OVER with ORDER BY and a ROWS frame gives a cumulative total in one pass. I specify ROWS explicitly so ties on the order column do not share a value."

#sql#window-functions#running-total#coding

Related questions

Practise more SQL & DBMS questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open SQL & DBMS quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.