// window reference

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.

カテゴリ
ウィンドウ
Returns
per-frame count
In this category
57 of 79

構文

COUNT(*) OVER (ORDER BY price RANGE BETWEEN 10 PRECEDING AND 10 FOLLOWING)

エンジンサポート

エンジンSupportメモ
SQL Server Not built in RANGE supports only UNBOUNDED PRECEDING/CURRENT ROW ends; no numeric or interval offsets
PostgreSQL はい Supported under this name.
MySQL はい MySQL 8.0+
SQLite はい SQLite 3.28+
Oracle はい Supported under this name.

例

PostgreSQL

SELECT product, price,
       COUNT(*) OVER (ORDER BY price RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS competing_products
FROM products;

知っておくと便利なこと

  • 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.

Cheat sheets for the engines that have it: 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.