Hard Window functions and CASE Shop database

Running total with SUM() OVER

Question

List the orders by date and show each order's id, ordered_on, and a running count of orders up to and including that one.

customersid, name, country, joined_on
productsid, name, category, price
ordersid, customer_id, ordered_on, status
order_itemsorder_id, product_id, quantity

Your query

Ctrl+Enter to run

Result

Press Run to see your query's result, or Check answer to compare it with the expected result.

Expected result

idordered_onorders_so_far
12024-07-011
22024-07-032
32024-07-093
42024-07-124
52024-07-155
62024-07-206
72024-07-227

The row order matters for this question.

Hint

COUNT(*) OVER (ORDER BY ...) counts the rows from the first one up to the current row.

Show the solution
solution.sql Run this code
SELECT id, ordered_on,
       COUNT(*) OVER (ORDER BY ordered_on, id) AS orders_so_far
FROM orders
ORDER BY ordered_on, id;

Why it works

With ORDER BY inside OVER, the window grows row by row from the start, so the count goes 1, 2, 3 and so on. The same pattern with SUM(amount) gives a running total of money.

Common mistake

Ordering the window only by a column with ties (two orders on the same day) makes those rows share a count. Add a unique column such as id to the ORDER BY.

Want to try the query on MySQL or PostgreSQL? Open it in the SQL Online Compiler or SQLite Online.