← Back to SQL, page 21

sql-0414 · Hard senior

Predict the running totals: SELECT x, SUM(x) OVER (ORDER BY x) over the values 1, 2, 2, 3.

The totals are 1, 5, 5 and 8. With ORDER BY and no frame clause, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which includes all peers of the current row, so both 2s see the sum through both 2s.

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;
xrunningby_rows
111
253
255
388

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