SQL RANGE with numeric offsets
Numeric RANGE offsets select rows whose ORDER BY value lies within n of the current value: a value band, not a row count.
- Kategorie
- Fenster
- Returns
per-frame count- In this category
- 57 of 79
Syntax
COUNT(*) OVER (ORDER BY price RANGE BETWEEN 10 PRECEDING AND 10 FOLLOWING)
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Not built in | RANGE supports only UNBOUNDED PRECEDING/CURRENT ROW ends; no numeric or interval offsets |
| PostgreSQL | Ja | Supported under this name. |
| MySQL | Ja | MySQL 8.0+ |
| SQLite | Ja | SQLite 3.28+ |
| Oracle | Ja | Supported under this name. |
Beispiele
PostgreSQL
SELECT product, price,
COUNT(*) OVER (ORDER BY price RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS competing_products
FROM products;
Gut zu wissen
- The ORDER BY expression must be numeric (or a type with engine support for offset arithmetic) and there must be exactly one ORDER BY expression in the window.
- Ties are always inside the band: every peer of the current row is included because its value equals the current value, whatever the offset.
- SQL Server is the outlier: its RANGE accepts only UNBOUNDED PRECEDING AND CURRENT ROW, so any value-band window must be rewritten with a self-join or ROWS approximation.
Questions about RANGE Numeric Offsets
How is a numeric RANGE offset different from ROWS n PRECEDING?
ROWS counts positions; RANGE measures value distance. With prices 9, 10, 11, 15, the row at 10 with BETWEEN 1 PRECEDING AND 1 FOLLOWING sees 9, 10 and 11 under RANGE; at 15 (the last row), RANGE sees only 15 while ROWS takes 11 and 15.
Why does my RANGE offset query error on SQL Server?
SQL Server's RANGE clause supports only UNBOUNDED and CURRENT ROW boundaries: no offsets at all. Approximate with ROWS, or self-join on the value band.
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: 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.