// window reference

SQL OVER clause

OVER defines which rows a window function sees: an empty OVER () covers the whole result, PARTITION BY splits it, ORDER BY orders each split, and a frame bounds it further.

Categoria
Janela
Returns
per-row aggregate or rank
In this category
41 of 79

Sintaxe

fn() OVER () | fn() OVER (PARTITION BY g) | fn() OVER (PARTITION BY g ORDER BY d [frame])

Suporte a mecanismos

MotorSupportNotas
SQL Server Sim Supported under this name.
PostgreSQL Sim Supported under this name.
MySQL Sim MySQL 8.0+
SQLite Sim SQLite 3.25+; full frames since 3.28+
Oracle Sim Supported under this name.

Exemplos

Any engine

SELECT employee_id, department, salary,
       COUNT(*) OVER () AS total_employees,
       COUNT(*) OVER (PARTITION BY department) AS dept_employees,
       SUM(salary) OVER (PARTITION BY department ORDER BY salary) AS running_dept
FROM employees;

Bom saber

  • The three shapes mean different things: no ORDER BY and no frame gives the whole partition; ORDER BY without a frame gives the default RANGE frame to the current row; an explicit frame overrides both.
  • The named WINDOW clause (WINDOW w AS (...), then OVER w) works on all five current engines, but arrived late on two: SQL Server 2022 and Oracle 21c. Older versions of both need every OVER written inline.
  • An aggregate with OVER keeps every row; the same aggregate without OVER collapses them. The only syntactic difference is the OVER clause itself.

Questions about OVER Clause

What does an empty OVER () mean?

The frame is the entire result set: every row sees every row. COUNT(*) OVER () is the total row count, SUM(x) OVER () the grand total (handy for shares and percentages).

Do I always need ORDER BY inside OVER?

For ROW_NUMBER, RANK and LAG/LEAD, SQL Server and Oracle require it; PostgreSQL, MySQL and SQLite accept ROW_NUMBER() OVER () but number rows in whatever order they arrive. Aggregates accept it optionally, and adding it changes the default frame from the whole partition to a running one.

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.