← Back to SQL, page 6

sql-0115 · Easy fresher

Write a query that shows a running total of daily sales.

Use SUM(amount) OVER (ORDER BY day). With an ORDER BY in the window, the default frame runs from the first row up to the current row, so each row shows the total so far. Add PARTITION BY to restart the total per group, such as per store or per month.

Full answer
sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
sql
SELECT day, amount,
       SUM(amount) OVER (ORDER BY day) AS running_total
FROM daily_sales
ORDER BY day;
dayamountrunning_total
2026-03-01120120
2026-03-0280200
2026-03-03150350
2026-03-0590440
2026-03-0660500
2026-03-09200700

Each row's running_total is the sum of all amounts up to and including that day. The ORDER BY inside OVER defines the order of accumulation; the ORDER BY at the end only decides the display order.

To restart the total each month, partition by month:

sql
SELECT day, amount,
       SUM(amount) OVER (PARTITION BY substr(day, 1, 7) ORDER BY day) AS month_to_date
FROM daily_sales
ORDER BY day;
dayamountmonth_to_date
2026-03-01120120
2026-03-0280200
2026-03-03150350
2026-03-0590440
2026-03-0660500
2026-03-09200700

All the March days are in one month here, so the result matches, but the partition would reset the total on 1 April.

For running totals, writing the frame explicitly is a good habit, because the default frame (RANGE) treats rows with the same ORDER BY value as one step:

text
SUM(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

With a unique day, ROWS and RANGE give the same numbers. With duplicate keys they do not.

sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);

SELECT day, amount,
       SUM(amount) OVER (ORDER BY day) AS running_total
FROM daily_sales
ORDER BY day;

SELECT day, amount,
       SUM(amount) OVER (PARTITION BY substr(day, 1, 7) ORDER BY day) AS month_to_date
FROM daily_sales
ORDER BY day;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • SUM(x) OVER (ORDER BY ...) gives a running total
  • The window's ORDER BY sets the accumulation order
  • PARTITION BY restarts the total per group
  • Write the ROWS frame explicitly when order keys can repeat

Common mistakes

  • Using a self join or correlated subquery for running totals on large tables
  • Confusing the window ORDER BY with the query's ORDER BY

Follow-ups

  • What changes if two rows have the same day?
  • How would you compute a 3-day moving average?

Tips

  • Mention the frame; it is what separates a good answer