SQL ORDER BY inside OVER
Orders rows within each partition: it defines ROW_NUMBER sequence, tie behaviour and the default frame for aggregates.
- Kategorie
- Fenster
- Returns
per-row value- In this category
- 44 of 79
Syntax
ROW_NUMBER() OVER (ORDER BY d) | SUM(x) OVER (ORDER BY d)
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+ |
| Oracle | Ja | Supported under this name. |
Beispiele
Any engine
SELECT day, price,
ROW_NUMBER() OVER (ORDER BY day) AS rn,
MAX(price) OVER (ORDER BY day) AS running_max
FROM prices;
Gut zu wissen
- Adding ORDER BY to an aggregate changes its meaning: SUM(x) OVER (PARTITION BY g) is the group total, SUM(x) OVER (PARTITION BY g ORDER BY d) is a running total; the frame appears silently.
- With ORDER BY and no frame, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which includes peers (the root of the LAST_VALUE surprise).
- Multiple window functions in one SELECT can each carry a different ORDER BY; each distinct ordering usually costs its own sort.
Questions about ORDER BY in OVER
Is ORDER BY required inside OVER?
On SQL Server and Oracle, yes for ranking functions and LAG/LEAD ('must have an OVER clause with ORDER BY', ORA-30485). PostgreSQL, MySQL and SQLite run them without it, in an arbitrary order, which is rarely what you want. Aggregates work without it and then cover the whole partition.
Does OVER (ORDER BY ...) replace the outer ORDER BY?
No. The inner one orders the window logic only; the final result order is undefined unless the query ends with its own ORDER BY.
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.