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.
- Categoria
- Janela
- Returns
n/a (clause semantics)- In this category
- 46 of 79
Sintaxe
SELECT ..., ROW_NUMBER() OVER (ORDER BY x) AS rn FROM t ORDER BY other_col
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | Supported under this name. |
| PostgreSQL | Sim | Supported under this name. |
| MySQL | Sim | MySQL 8.0+ |
| SQLite | Sim | SQLite 3.25+ |
| Oracle | Sim | Supported under this name. |
Exemplos
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;
Bom saber
- 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.
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.