Chapter 7 · Lesson 3 of 6
Running Totals with ORDER BY
Build running totals by adding ORDER BY inside OVER, and calculate cumulative sales for each salesperson over time.
Adding ORDER BY inside the window makes the function care about row sequence.
That is how you build running totals:
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_2The 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.
Sample data
This lesson loads the sales_2 table (16 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for sales_2
CREATE OR REPLACE TABLE sales_2 (
id INTEGER,
salesperson VARCHAR,
region VARCHAR,
amount DECIMAL(10,2),
quantity INTEGER,
sale_date DATE
);
INSERT INTO sales_2 VALUES
(1, 'Alice', 'West', 1200, 3, '2024-01-05'),
(2, 'Bob', 'East', 850, 2, '2024-01-08'),
(3, 'Alice', 'West', 640, 1, '2024-01-11'),
(4, 'Diana', 'South', 430, 5, '2024-01-12'),
(5, 'Eve', 'West', 1500, 4, '2024-02-01'),
(6, 'Frank', 'East', 920, 2, '2024-02-03'),
(7, 'Grace', 'North', 760, 2, '2024-02-07'),
(8, 'Bob', 'East', 1100, 3, '2024-02-10'),
(9, 'Alice', 'West', 780, 2, '2024-03-02'),
(10, 'Bob', 'East', 990, 3, '2024-03-05'),
(11, 'Diana', 'South', 610, 2, '2024-03-08'),
(12, 'Eve', 'West', 700, 1, '2024-03-12'),
(13, 'Frank', 'East', 1150, 4, '2024-03-15'),
(14, 'Grace', 'North', 840, 2, '2024-03-18'),
(15, 'Alice', 'West', 1320, 5, '2024-04-01'),
(16, 'Bob', 'East', 730, 1, '2024-04-05');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.
Hint: Use SUM(amount) OVER (PARTITION BY salesperson ORDER BY sale_date ...) AS running_amount.
Run your query in the editor and the lesson checks the result automatically.
Lessons in Window Functions
Calculate totals, running sums, rankings, and previous-row comparisons with OVER and PARTITION BY while keeping every detail row.
Related guides
SQL Window Functions Explained: OVER, PARTITION BY, Running Totals, and LAG
Window functions add context beside each row: totals, group totals, ranks, running totals, and previous values without losing detail.
Parquet vs CSV for SQL Analysis: Types, Columnar Reads, and Memory Limits
Parquet stores typed columns that engines can read selectively. See what that means for SQL analysis and where browser memory still sets the limit.