Window Functions and Ranking
Rank rows within groups while preserving individual rows.
database, postgresql, sql, window functions, rank, partitionsCompare rows without collapsing them
An aggregate with GROUP BY normally produces one row per group. A window
function instead computes a value over a set of related rows while retaining
the individual rows. PARTITION BY defines the groups for the calculation,
and the window's ORDER BY defines ranking order.
SQL illustration
This self-contained PostgreSQL query uses fictional values:
WITH books(author, title, pages) AS (
VALUES ('Ada', 'Kite', 120), ('Ada', 'Oak', 120),
('Ada', 'Reef', 80), ('Bo', 'Tide', 200)
)
SELECT author, title, pages,
RANK() OVER (PARTITION BY author ORDER BY pages DESC) AS position
FROM books
ORDER BY author, pages DESC, title;
Prepared result — not live execution:
| author | title | pages | position |
|---|---|---|---|
| Ada | Kite | 120 | 1 |
| Ada | Oak | 120 | 1 |
| Ada | Reef | 80 | 3 |
| Bo | Tide | 200 | 1 |
Ada's two 120-page books tie at rank 1, so her next rank is 3. Bo's
partition starts at 1 independently. The final ORDER BY sorts the output;
title breaks the display tie without changing the rank calculation.
See the reasoning
Rank within each partition
Follow ties and the gap in RANK while retaining each row. This is prepared; Intuvo does not run SQL.
Start Ada's partition
| author | title | pages | rank |
|---|---|---|---|
| Ada | Kite (current) | 120 | 1 |
| Ada | Oak | 120 | pending |
| Ada | Reef | 80 | pending |
| Bo | Tide | 200 | pending |
Kite's 120 pages receives rank 1 in Ada's partition.
Ordering, peers, and frames
ROW_NUMBER assigns distinct numbers; with ties, include an appropriate
tie-breaker in its window ordering if deterministic numbering is required.
DENSE_RANK gives ties the same rank without the gap left by RANK.
Aggregate windows and functions such as last_value can depend on the
frame inside a partition. Default frames can include peers and surprise
readers; specify ROWS or another suitable frame when the intended boundary
matters. A window ORDER BY is not a substitute for ordering the final result.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
