HomeInterview QuestionsSql, Cumulative Sum, Ordering

How do you order rows when calculating a cumulative sum in SQL?

🟡 Medium Conceptual Junior level
1 Times asked
Mar 2026 Last seen
Mar 2026 First seen

💡 Model Answer

To calculate a cumulative sum in SQL you use a window function with an ORDER BY clause that defines the sequence of rows over which the sum is accumulated. The syntax is typically: SELECT id, amount, SUM(amount) OVER (ORDER BY date ROWS UNBOUNDED PRECEDING) AS cumulative_amount FROM transactions;. The ORDER BY clause ensures that the rows are processed in the correct chronological or logical order. If you need to reset the cumulative sum for each group (e.g., per customer), you add a PARTITION BY clause: SUM(amount) OVER (PARTITION BY customer_id ORDER BY date). The ROWS UNBOUNDED PRECEDING clause is optional in many engines because it is the default; it tells the engine to include all rows from the start of the partition up to the current row. Using these clauses correctly guarantees that the cumulative sum reflects the intended business logic, such as running balances or progressive totals.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.

Get Assisting AI — Starts at ₹500