SQL UNBOUNDED PRECEDING and FOLLOWING
An unbounded frame stretches from the first to the last row of the partition, making offset functions see the whole window.
- Категория
- Окно
- Returns
per-partition value- In this category
- 52 of 79
Синтаксис
LAST_VALUE(x) OVER (ORDER BY d ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
Поддержка движка
| Движок | 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. |
Примеры
PostgreSQL
SELECT trade_day, tick_time, price,
FIRST_VALUE(price) OVER w AS open_price,
LAST_VALUE(price) OVER w AS close_price,
MAX(price) OVER w AS day_high
FROM ticks
WINDOW w AS (PARTITION BY trade_day ORDER BY tick_time
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING);
Полезно знать
- Without it, LAST_VALUE and NTH_VALUE silently return the current row or NULL: the default frame ends at the current row, so they never see what comes after. This frame is the canonical fix.
- One-sided frames are valid: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW is the running-total frame; ... AND 1 PRECEDING excludes the current row from its own sum.
- Aggregates over a fully unbounded frame equal the same aggregate with no ORDER BY at all; the frame clause only matters when you also need the offset functions or mixed windows.
Questions about UNBOUNDED Frame
Why does FIRST_VALUE work but LAST_VALUE fail by default?
FIRST_VALUE's target row is always inside the default frame (it is the first); the last row of a frame ending at CURRENT ROW is the current row itself, so LAST_VALUE returns it. Stretch the frame to see the real last row.
Is an unbounded frame expensive?
Not for aggregates: the result is the same for every row of the partition, so engines compute it once. The cost is the sort. Sliding frames are the expensive ones for MIN and MAX, which cannot subtract the row leaving the frame and may rescan it per row.
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.