// window reference

SQL OVER ORDER BY vs outer ORDER BY

OVER (ORDER BY x) defines the logical order within partitions for window computation; the query's ORDER BY sorts the final rows. Neither implies the other.

Категория
Окно
Returns
n/a (clause semantics)
In this category
46 of 79

Синтаксис

SELECT ..., ROW_NUMBER() OVER (ORDER BY x) AS rn FROM t ORDER BY other_col

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

Движок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 department, employee_id, salary,
       ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank
FROM employees
ORDER BY department, dept_rank;

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

  • A rank computed in a query level can be used by that level's SELECT list and ORDER BY, but not by its WHERE, GROUP BY or HAVING.
  • Removing the outer ORDER BY means the result can come back in any order, even though ROW_NUMBER was computed over an order. Ranks are values, not a row guarantee.
  • If the outer ORDER BY matches the window's PARTITION BY and ORDER BY, the engine can often reuse the window's sort instead of sorting twice.

Questions about OVER ORDER BY vs Outer ORDER BY

Why are my ranked rows not in rank order?

You ranked inside OVER but never sorted the result: window ORDER BY does not order output. Add an outer ORDER BY on the rank (or the base column) to display in order.

Can the two ORDER BYs differ?

Yes, and sometimes should: rank by amount descending but present alphabetically. The window order controls the numbers; the outer order controls the rows you see.

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.