Learn SQL Lesson

Running Totals with ORDER BY

Adding `ORDER BY` inside the window makes the function care about row sequence.

That is how you build running totals:

~~~sql SELECT salesperson, sale_date, amount, SUM(amount) OVER ( PARTITION BY salesperson ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_amount FROM sales_2 ~~~

The frame clause `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW` says: start at the first row in this salesperson's partition and keep summing up to the current row.

Writing the frame explicitly avoids surprises. Some databases use a default frame when you add `ORDER BY`, and duplicate ordering values can make that default behave differently than a row-by-row running total.

This pattern is common in finance, analytics, and product dashboards whenever you want a cumulative view over time.

Practice challenge

For each salesperson, show their cumulative sales over time. Return salesperson, sale_date, amount, and running_amount, ordered by salesperson and sale_date.

Open interactive editor