// aggregates reference

SQL aggregates with OVER window

Window aggregates compute a group statistic but hand it to every row instead of collapsing the group.

Kategorie
Aggregates
Returns
same as the aggregate
In this category
44 of 52

Syntax

SUM(x) OVER (PARTITION BY g) | SUM(x) OVER (ORDER BY d)

Engine-Unterstützung

EngineSupportNotizen
SQL Server Ja Supported under this name.
PostgreSQL Ja Supported under this name.
MySQL Ja Supported under this name.
SQLite Ja Supported under this name.
Oracle Ja Supported under this name.

Beispiele

Any engine

SELECT order_id, SUM(total) OVER (PARTITION BY customer_id) AS lifetime FROM orders;

PostgreSQL

SELECT order_id, SUM(total) OVER (ORDER BY order_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM orders;

SQL Server

SELECT AVG(total) OVER (PARTITION BY customer_id) AS avg_order FROM orders;

Gut zu wissen

  • Unlike GROUP BY, the window form never collapses rows: detail and total sit side by side.
  • With ORDER BY in the OVER clause, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so rows with tied ORDER BY values all get the same total; use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for a strict running total.
  • PARTITION BY without ORDER BY gives the group total on every row of the partition.
  • SUM over an all-NULL window returns NULL, not 0.

Questions about OVER

OVER vs GROUP BY for SUM?

GROUP BY returns one row per group; OVER keeps every row and annotates it with the group statistic.

Why does my running total jump?

The default RANGE frame includes peer rows with equal ORDER BY values; switch to ROWS for one-row-at-a-time totals.

Do NULLs count in window aggregates?

The same rules as plain aggregates: NULLs are skipped and an all-NULL window returns NULL for SUM and AVG.

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.