liveBook · Manning

Rank function

As explained in Just Use Postgres!

A rank function assigns ordinal rankings to rows according to an ordering and gives tied rows the same rank.

A rank function assigns ordinal positions to rows according to an ordering. RANK() is a window function: it orders results while retaining each row, and tied rows receive the same rank. section 3.5

Ranking songs by total play duration

Aggregate plays by song, then rank the totals from largest to smallest: SELECT song_id, SUM(play_duration) AS total_play_duration, RANK() OVER (ORDER BY SUM(play_duration) DESC) AS song_rank FROM streaming.plays GROUP BY song_id ORDER BY song_rank; The output ranks song 4 first with 1, song 1 second with 2, and song 5 tenth with 10. section 3.5

Listing 3.14 Ranking songs by total play duration
SELECT song_id, SUM(play_duration) AS total_play_duration,
RANK() OVER (ORDER BY SUM(play_duration) DESC) AS song_rank
FROM streaming.plays
GROUP BY song_id
ORDER BY song_rank;

Inspect the complete SQL listing for ranking songs by total play duration. section 3.5

How Just Use Postgres! covers it

How deep it goes
Explains the RANK() query pattern and output, but does not develop ranking internals or extensive tie behavior.
Examples
Uses a music-streaming dataset to rank songs by their total play duration.
What it assumes
Builds on SQL aggregation with SUM(), GROUP BY, and ordering with ORDER BY.
What you can do after
Apply it via SQL to produce ordered ranks alongside grouped aggregate results.
How it connects
Connects RANK() with window functions, ORDER BY, SUM(), and GROUP BY.

Also explained in

Compare how 2 books explain rank 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.