// window reference

SQL ROWS frame

A ROWS frame bounds the window by row count: each boundary is a position relative to the current row, unaffected by ties in the ORDER BY.

类别
窗口
Returns
per-frame aggregate
In this category
51 of 79

语法

SUM(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) | ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING

引擎支持

引擎Support备注
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 MySQL 8.0+
SQLite 是 SQLite 3.25+
Oracle 是 Supported under this name.

示例

Any engine

SELECT day, price,
       AVG(price) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7,
       MAX(price) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS high_so_far
FROM prices;

值得了解

  • ROWS is immune to the peers problem: duplicate ORDER BY values each get their own frame end, unlike RANGE. That determinism is why most sliding windows use ROWS.
  • Early rows see truncated frames: ROWS BETWEEN 6 PRECEDING AND CURRENT ROW averages 1 row on the first row, 2 on the second, and so on.
  • A frame may not run backwards: ROWS BETWEEN 3 FOLLOWING AND 1 PRECEDING is an error. Start boundary must not come after the end boundary.

Questions about ROWS Frame

ROWS or RANGE: which should I write?

ROWS when the window is a number of rows (the last 7 observations), RANGE when it is a value span (all peers, or a date interval). ROWS with a unique ORDER BY is the most predictable.

How do NULLs affect a ROWS frame?

They still take up positions: a 7-row frame with two NULLs holds 7 rows, but AVG divides by the 5 non-NULL values and COUNT(x) returns 5 while COUNT(*) returns 7.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.