liveBook · Manning

Window function

As explained in Just Use Postgres!

A window function computes a value over a set of rows related to the current row without collapsing those rows into a single aggregate result.

A window function calculates a value across rows related to the current row while retaining every row in the output. The OVER clause divides rows into windows, and the function operates within each window. section 3.5

SELECT function_name(arguments)
OVER (PARTITION BY columnA)
FROM table;

Use PARTITION BY to place rows with the same value into a window, then apply an aggregate such as SUM or AVG, or a built-in function such as RANK or ROW_NUMBER. section 3.5

Keep users while calculating song totals

A grouped aggregate returns one row per song. A window function keeps each song-user row and repeats the song total: WITH plays_with_total AS ( SELECT song_id, user_id, SUM(play_duration) OVER (PARTITION BY song_id) AS total_duration FROM streaming.plays ) SELECT DISTINCT song_id, user_id, total_duration FROM plays_with_total ORDER BY song_id, user_id; The result includes users 1, 2, and 3 for song 1, each with a total duration of 800, and users for song 2, each with 654. section 3.5

Common applications include:

  • The broader pattern supports sorting, cumulative sums, moving averages, and lag or lead analysis. section 3.5

How Just Use Postgres! covers it

How deep it goes
Defines windows, contrasts them with GROUP BY aggregates, and demonstrates partitioning, ordering, running totals, and ranking.
Examples
Demonstrates song totals by user, running play-duration totals, and song rankings using streaming-play data.
What it assumes
Builds from grouped aggregate queries and contrasts their one-row-per-group output with row-preserving window results.
What you can do after
Apply via PostgreSQL to write readable queries that calculate grouped, cumulative, and ranked values without collapsing detail rows.
How it connects
Connects window functions with aggregate functions, GROUP BY, CTEs, self-joins, ranking, running totals, and lag-lead analysis.

Also explained in

Compare how 3 books explain window function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Just Use Postgres!. The section links point to the parts of the book it draws on.