// window reference

SQL named WINDOW clause

WINDOW w AS (...) declares a window once; functions reference it with OVER w, and definitions can extend other definitions.

Категория
Окно
Returns
named window definition
In this category
63 of 79

Синтаксис

SELECT ... OVER w FROM t WINDOW w AS (PARTITION BY g ORDER BY d), w2 AS (w ORDER BY d2)

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

ДвижокSupportЗаметки
SQL Server Да SQL Server 2022+ and Azure SQL; earlier versions need every OVER written out
PostgreSQL Да Supported under this name.
MySQL Да MySQL 8.0+
SQLite Да SQLite 3.25+; one window built on another since 3.28
Oracle Да Oracle 21c+

Примеры

Any engine

SELECT department, employee_id, salary,
       RANK() OVER (w ORDER BY salary DESC) AS salary_rank,
       SUM(salary) OVER (w ORDER BY hire_date) AS running_payroll,
       AVG(salary) OVER w AS dept_avg
FROM employees
WINDOW w AS (PARTITION BY department);

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

  • A reference may add only what the base window leaves out: with w AS (PARTITION BY g), both OVER (w ORDER BY x) and w2 AS (w ORDER BY x) are legal. If w already has an ORDER BY, adding another fails ('cannot override ORDER BY clause of window').
  • A window built on another can never re-specify PARTITION BY, and a window that has a frame clause cannot be extended at all (PostgreSQL: 'cannot copy window because it has a frame clause'); only a bare OVER w can use it.
  • Put the shared PARTITION BY in the named window and the ORDER BY at each use; that is the shape that keeps one definition useful for ranks, running totals and plain partition aggregates.

Questions about WINDOW Clause

Why does my engine reject OVER (w ORDER BY ...)?

Because w already has an ORDER BY or a frame clause, and a reference cannot override either. Move the ORDER BY out of w and add it at each use, as in the example.

Which SQL Server versions have the WINDOW clause?

SQL Server 2022 and later, plus Azure SQL Database. On 2019 and earlier there is none, and every window function repeats its full OVER (...) inline.

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.