// window reference

SQL window functions vs GROUP BY

GROUP BY returns one row per group; window functions return every row with the group's aggregate attached. Pick per output shape, not per calculation.

Категория
Окно
Returns
rows or groups
In this category
37 of 79

Синтаксис

SELECT g, SUM(x) FROM t GROUP BY g | SELECT g, id, SUM(x) OVER (PARTITION BY g) FROM t

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

Движок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

-- collapsed
SELECT department, SUM(salary) AS payroll
FROM employees GROUP BY department;

Any engine

-- annotated: detail rows plus their group's payroll
SELECT department, employee_id, salary,
       SUM(salary) OVER (PARTITION BY department) AS payroll
FROM employees;

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

  • Detail columns force the choice: SELECT g, id, SUM(x) FROM t GROUP BY g is invalid (id is not grouped); the window form keeps id because nothing collapses.
  • Together they compose: with GROUP BY present, window functions evaluate over the grouped rows, so SUM(SUM(x)) OVER () totals the group sums.
  • HAVING filters groups before windows compute; to filter on a window result you need the CTE wrap, not HAVING.

Questions about Window vs GROUP BY

Which is faster, GROUP BY or a window?

Different jobs: GROUP BY shrinks the result, windows sort per partition and keep it. If the caller only wants per-group numbers, GROUP BY (or a GROUP BY joined back) is cheaper; windows win when detail rows are the point.

Can I use both in one query?

Yes, windows run after GROUP BY, so aggregates inside OVER see the grouped values: AVG(SUM(x)) OVER (ORDER BY dim) is a running average of group sums.

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.