SQL aggregate functions with OVER
Any aggregate function gains an OVER clause to become a window aggregate: the rows stay, and each one carries the aggregate of its frame or partition.
- Categoría
- Ventana
- Returns
type of the aggregate- In this category
- 21 of 79
Sintaxis
SUM(x) OVER (PARTITION BY g) | COUNT(*) OVER ()
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | Supported under this name. |
| PostgreSQL | Sí | Supported under this name. |
| MySQL | Sí | MySQL 8.0+; only some aggregates (COUNT, SUM, AVG, MIN, MAX, STDDEV, VARIANCE, BIT_*, JSON aggregates) work as windows |
| SQLite | Sí | SQLite 3.25+; all built-in aggregates including group_concat work |
| Oracle | Sí | Supported under this name. |
Ejemplos
Any engine
SELECT department, salary,
SUM(salary) OVER (PARTITION BY department) AS dept_total,
AVG(salary) OVER (PARTITION BY department) AS dept_avg
FROM employees;
Any engine
SELECT order_id, amount,
amount * 100.0 / SUM(amount) OVER () AS pct_of_revenue
FROM orders;
Conviene saberlo
- Aggregates in the same SELECT as GROUP BY run over the groups, not the rows: SUM(SUM(x)) OVER () is the legal way to total group sums, a frequent 'invalid column' confusion.
- The empty OVER () means the whole result set: COUNT(*) OVER () is the total row count on every row, useful for ratios and progress bars.
- FILTER (WHERE ...) after the aggregate is the clean conditional form on PostgreSQL, SQLite 3.30+ and Oracle 23.26.1+; on SQL Server and MySQL put a CASE inside the aggregate.
Questions about Aggregates with OVER
Why use SUM OVER instead of GROUP BY?
GROUP BY collapses to one row per group; SUM OVER stamps the group total on every row. They can even coexist: with GROUP BY in the query, window aggregates run over the grouped results.
Which aggregates can be window functions?
Nearly every built-in aggregate on PostgreSQL, Oracle and SQLite (PostgreSQL excludes ordered-set aggregates such as PERCENTILE_CONT). SQL Server allows the numeric ones but not STRING_AGG. MySQL allows COUNT, SUM, AVG, MIN, MAX, the STDDEV/VARIANCE family, BIT_* and the JSON aggregates, but not GROUP_CONCAT.
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.