Skip to main content

From an orders table with order_id, customer_id, order_date and amount, show each order with the running total of that customer's spend so far. For example, a customer with orders of 100, 50 and 25 gets running totals of 100, 150 and 175.

Coding rounds · Intermediate 2

Short answer

Use a window sum: SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date, order_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). PARTITION BY restarts the total per customer. The ROWS frame and the order_id tiebreaker stop orders on the same date from sharing one total. Cost is a sort, O(n log n).

Deeper answer

First clarify the grain. Ask whether the total restarts for each customer, whether two orders can share the same order_date, and whether you want one row per order or one per day. Ask whether refunds are stored as negative amounts.

The query is SELECT order_id, customer_id, order_date, amount, SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date, order_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total FROM orders. A window function keeps every row, unlike GROUP BY, which collapses them. The frame clause matters. With ORDER BY and no frame, the default is RANGE up to the current row, and RANGE treats rows with equal ORDER BY values as peers. Two orders on the same date would then both show the total after both orders. ROWS counts physical rows, and adding order_id makes the order fixed.

The database sorts each partition once, so the cost is about O(n log n). Test two orders on the same date, a customer with one order and a negative amount.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

SQL for engineers

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.