Running count
COUNT(*) over a growing frame: the same numbers as ROW_NUMBER on a unique sort, different ones on ties.
The task
You want to see, next to each order, how many orders have been placed up to and including that point in time.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT order_date, id,
COUNT(*) OVER (ORDER BY order_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS orders_so_far
FROM orders
ORDER BY order_date, id;
Cómo funciona
COUNT(*) with an ordered window frame counts every row from the start of the partition through the current one. Ordered by a unique key it is identical to ROW_NUMBER, but it reads as what it is. The difference appears when you drop the unique tiebreaker and keep the default RANGE frame: peers are all counted at once, so the count stays flat across tied rows and then jumps.
Variations
Running count per customer
SELECT customer_id, order_date,
COUNT(*) OVER (PARTITION BY customer_id
ORDER BY order_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS orders_so_far
FROM orders
ORDER BY customer_id, order_date;
Questions that come up
When is a running count better than ROW_NUMBER?
When rows share the ORDER BY key and you want all of them to show the same count. Drop the id tiebreaker and the ROWS clause, and the default RANGE frame gives every order on the same timestamp the count including all of them. Over a unique key, as written above, the two produce identical values.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.