// window reference

SQL ORDER BY inside OVER

Orders rows within each partition: it defines ROW_NUMBER sequence, tie behaviour and the default frame for aggregates.

Категория
Окно
Returns
per-row value
In this category
44 of 79

Синтаксис

ROW_NUMBER() OVER (ORDER BY d) | SUM(x) OVER (ORDER BY d)

Поддержка движка

Движок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.

Примеры

Any engine

SELECT day, price,
       ROW_NUMBER() OVER (ORDER BY day) AS rn,
       MAX(price) OVER (ORDER BY day) AS running_max
FROM prices;

Полезно знать

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

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.