// window reference

SQL RANGE frame

A RANGE frame includes rows whose ORDER BY value falls within an offset of the current value; ties are always in or out together.

Kategorie
Fenster
Returns
per-frame aggregate
In this category
56 of 79

Syntax

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

Engine-Unterstützung

EngineSupportNotizen
SQL Server Different name or syntax RANGE with UNBOUNDED PRECEDING/FOLLOWING and CURRENT ROW only; no value offsets
PostgreSQL Ja Supported under this name.
MySQL Ja MySQL 8.0+
SQLite Ja SQLite 3.25+; RANGE offsets since 3.28
Oracle Ja Supported under this name.

Beispiele

PostgreSQL

SELECT sensor_id, reading_time, value,
       AVG(value) OVER (PARTITION BY sensor_id
                        ORDER BY reading_time
                        RANGE BETWEEN INTERVAL '5 minutes' PRECEDING
                                  AND CURRENT ROW) AS avg_5min
FROM readings;

MySQL

-- numeric offsets: PostgreSQL, MySQL, SQLite 3.28+ and Oracle, not SQL Server
SELECT bid, price,
       COUNT(*) OVER (ORDER BY price RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS nearby_bids
FROM orderbook;

Gut zu wissen

  • RANGE requires exactly one ORDER BY expression when using offsets (a value span is only defined against one column); UNBOUNDED/CURRENT ROW forms work with multi-key sorts.
  • The default frame of every ordered window is a RANGE frame, so RANGE semantics are already in your queries even if you never write the word.
  • Numeric offsets compare values, not rows: RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING on integers covers values v-1 through v+1, peers included.

Questions about RANGE Frame

When is RANGE required instead of ROWS?

When the window is defined by value distance (a time interval, a price band, a percentile-like span) or when ties must move together. Row-count windows want ROWS.

Why does RANGE reject my two-column ORDER BY?

Offset boundaries need a single sortable value; with multiple keys there is no total order to measure distance in. Use ROWS, or keep offsets only on the primary key.

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.