Full answer
sql
WITH t(x) AS (VALUES (1), (2), (2), (3))
SELECT x, SUM(x) OVER (ORDER BY x) AS running, SUM(x) OVER (ORDER BY x ROWS UNBOUNDED PRECEDING) AS by_rows FROM t;| x | running | by_rows |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 5 | 3 |
| 2 | 5 | 5 |
| 3 | 8 | 8 |
The running column uses the default RANGE frame: rows with equal ORDER BY values are peers and enter the frame together, so the first 2 already counts the second one and shows 5. The by_rows column uses a ROWS frame, which stops at the physical current row and gives 1, 3, 5, 8. The order among the two peer rows is not defined, so which one shows 3 under ROWS can vary; add a unique tiebreaker to the ORDER BY when the running total must be stable. PostgreSQL follows the same standard default (PostgreSQL behaviour stated, not run here).
sql
WITH t(x) AS (VALUES (1), (2), (2), (3))
SELECT x, SUM(x) OVER (ORDER BY x) AS running, SUM(x) OVER (ORDER BY x ROWS UNBOUNDED PRECEDING) AS by_rows FROM t;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Default frame with ORDER BY is RANGE ... CURRENT ROW
- RANGE includes peers with equal values
- ROWS counts physical rows
- Add a tiebreaker for stable running totals
Common mistakes
- Expecting row-by-row totals with duplicate sort keys
Follow-ups
- When is RANGE the desired behaviour?
- How would you write a 3-row moving average?
Tips
- Look for ties in the ORDER BY