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.
- Kategorie
- Fenster
- Returns
rows or groups- In this category
- 37 of 79
Syntax
SELECT g, SUM(x) FROM t GROUP BY g | SELECT g, id, SUM(x) OVER (PARTITION BY g) FROM t
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Ja | Supported under this name. |
| PostgreSQL | Ja | Supported under this name. |
| MySQL | Ja | MySQL 8.0+ |
| SQLite | Ja | SQLite 3.25+ |
| Oracle | Ja | Supported under this name. |
Beispiele
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;
Gut zu wissen
- 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.
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.