Memra

Windows: aggregates that keep the rows

◈ 2 cards

Compute across a set of rows without collapsing them.

Aggregate without grouping

GROUP BY collapses rows. A window function computes across a set of rows but keeps every row — you get the detail and the summary side by side. The OVER () clause makes any aggregate a window:

SELECT title, price,
       AVG(price) OVER () AS avg_all
FROM books;

Every row now carries the overall average alongside its own price. PARTITION BY restarts the window per group — here, the average price within each genre:

SELECT title, genre, price,
       AVG(price) OVER (PARTITION BY genre) AS genre_avg
FROM books;
titlegenrepriceavg_allgenre_avgThe GlassForestfiction14.9916.6014.75Rivers of Saltfiction16.0016.6014.75Bright Hollowfiction13.2516.6014.75QuantumMorningsscience22.5016.6020.63Small Machinesscience18.7516.6020.63avg_all never changes; genre_avg changes at each partition.
GROUP BY would collapse these five rows into two. OVER () keeps them and staples the overall average (16.598 across all ten books, shown here rounded) onto each; PARTITION BY genre restarts the average at each genre boundary.
NORMAL ~/memra/learn/postgresql/window-basics utf-8 LF