SQL ROWS vs RANGE frames
ROWS treats each row individually; RANGE groups rows with equal ORDER BY values into one frame end. With unique sort keys they coincide.
- 类别
- 窗口
- Returns
frame type- In this category
- 58 of 79
语法
SUM(x) OVER (ORDER BY d ROWS UNBOUNDED PRECEDING) | SUM(x) OVER (ORDER BY d RANGE UNBOUNDED PRECEDING)
引擎支持
| 引擎 | 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
-- t holds (day 1, 100), (day 1, 100), (day 2, 50)
SELECT day, amount,
SUM(amount) OVER (ORDER BY day ROWS UNBOUNDED PRECEDING) AS rows_sum,
SUM(amount) OVER (ORDER BY day RANGE UNBOUNDED PRECEDING) AS range_sum
FROM t;
-- rows_sum: 100, 200, 250 range_sum: 200, 200, 250
值得了解
- They differ exactly when the ORDER BY has ties. Unique keys make ROWS and RANGE identical, which is why the bug hides until duplicate values appear.
- The default frame is RANGE (UNBOUNDED PRECEDING to CURRENT ROW); queries that assume ROWS behaviour without writing it are the classic latent bug.
- GROUPS is a third type on PostgreSQL 11+, SQLite 3.28+ and Oracle 21c+: its offsets count tie groups instead of rows or values.
Questions about ROWS vs RANGE
Which frame type is the default?
RANGE. ORDER BY without a frame clause means RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, peers included; spell out ROWS when you want row-by-row.
Do ROWS and RANGE differ in performance?
Rarely meaningfully; engines optimize both. Choose by semantics first, then measure; the expensive part is usually the sort that feeds the window.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.