What is a window function's frame clause (ROWS/RANGE BETWEEN), and how would you compute a running total or moving average?
Last updated
The frame clause sets which rows of the partition feed each row's window calculation. A running total uses
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and a moving average uses a fixed window likeROWS BETWEEN 6 PRECEDING AND CURRENT ROW.ROWScounts physical rows.RANGEtreats rows with the sameORDER BYvalue as peers, which can inflate running totals across ties.With
ORDER BYbut no explicit frame, the default isRANGE UNBOUNDED PRECEDING, a common surprise.
- https://datasciencehired.com/blog/calculate-moving-averages-sql/
- https://docs.databend.com/sql/sql-functions/window-functions/range-between
- https://medium.com/@Samietex/sql-window-functions-part-2-frames-percentiles-and-the-stuff-part-1-skipped-40e1e7193322
- https://oneuptime.com/blog/post/2026-02-17-how-to-use-window-functions-in-bigquery-for-running-totals-and-moving-averages/view
- https://www.tigerdata.com/learn/postgresql-window-functions
- https://learn.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql?view=sql-server-ver17
- https://www.freecodecamp.org/news/window-functions-in-sql/
- https://www.sqlnoir.com/blog/sql-window-functions