SQL frame offsets n PRECEDING and FOLLOWING
Offsets like 3 PRECEDING or 2 FOLLOWING place frame boundaries a fixed distance from the current row, enabling skip-current and lead-style windows.
- Kategorie
- Fenster
- Returns
per-frame aggregate- In this category
- 53 of 79
Syntax
SUM(x) OVER (ORDER BY d ROWS BETWEEN 2 PRECEDING AND 1 PRECEDING) | AVG(x) OVER (ORDER BY d ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING)
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Ja | Supported under this name. |
| PostgreSQL | Ja | Supported under this name. |
| MySQL | Ja | MySQL 8.0+ |
| SQLite | Ja | SQLite 3.25+ for ROWS offsets; RANGE offsets since 3.28 |
| Oracle | Ja | Supported under this name. |
Beispiele
Any engine
-- sum of the previous two rows, excluding the current one
SELECT day, units,
SUM(units) OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND 1 PRECEDING) AS prev_two
FROM daily_sales;
Gut zu wissen
- ROWS offsets must be non-negative integers (RANGE offsets can also be intervals on date types). Negative offsets are rejected, and only Oracle accepts a column as the offset.
- BETWEEN 1 PRECEDING AND 1 PRECEDING is legal: a one-row frame holding exactly the previous row, the aggregate form of LAG for numeric windows.
- FOLLOWING-ended frames shrink near the partition's end: CURRENT ROW AND 3 FOLLOWING covers fewer rows on the last rows, same as PRECEDING frames shrink at the start.
Questions about n PRECEDING / n FOLLOWING
Can the offset be a column?
Only on Oracle, which evaluates it per row: ROWS BETWEEN g PRECEDING AND CURRENT ROW runs there. PostgreSQL says 'argument of ROWS must not contain variables', SQLite requires a constant non-negative integer, and SQL Server and MySQL accept only a literal (MySQL also a ? parameter). For a per-row window size, use a correlated subquery or a self-join instead.
How do I exclude the current row from a running sum?
End the frame at 1 PRECEDING: ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING. Common for 'total of everything before me' logic.
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.