SQL window function in ORDER BY
The final ORDER BY may reference window functions (or their aliases) directly; the result is sorted after the windows compute.
- Categoria
- Janela
- Returns
ordered result- In this category
- 40 of 79
Sintaxe
SELECT name, RANK() OVER (ORDER BY score DESC) AS r FROM players ORDER BY r
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 product, category, price,
RANK() OVER (PARTITION BY category ORDER BY price DESC) AS cat_rank
FROM products
ORDER BY category, cat_rank;
Bom saber
- ORDER BY inside OVER orders rows within the window; the outer ORDER BY orders the final result. They are independent and usually must match for ranks to display in order.
- The outer query of a subquery or CTE can only sort by window results the inner query projected as columns; it cannot reach the inner window expression itself.
- All five engines accept a bare alias in ORDER BY (ORDER BY cat_rank). Inside an expression they differ: ORDER BY CASE WHEN cat_rank = 1 THEN 0 ELSE 1 END fails on SQL Server ('Invalid column name') and PostgreSQL ('column does not exist'), so repeat the window call or use a CTE.
Questions about Window in ORDER BY
Why can I sort by RANK in ORDER BY but not filter in WHERE?
Evaluation order: windows are computed after WHERE and before the final ORDER BY, so ORDER BY sees them and WHERE cannot. Filter through a CTE instead.
Does ORDER BY inside OVER double-sort the query?
It defines the partition's logical order and usually forces a sort per window definition. Sharing one named window (WINDOW clause) for several functions lets the engine reuse it.
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.