Reading preferences
Concept

Window Functions and Ranking

Rank rows within groups while preserving individual rows.

database, postgresql, sql, window functions, rank, partitions

Compare 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:

authortitlepagesposition
AdaKite1201
AdaOak1201
AdaReef803
BoTide2001

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

Ranks revealed by partition
authortitlepagesrank
AdaKite (current)1201
AdaOak120pending
AdaReef80pending
BoTide200pending

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.

1. What happens to the individual rows in this ranking example?
2. What does PARTITION BY author do here?
3. What ranks do Ada's three books receive?
4. Does ORDER BY inside OVER alone guarantee final result order?

References and further reading