AI Hints
Home›PostgreSQL Tutorial›Window Functions
PostgreSQL · Lesson 32 of 120

Top N per Group

Ranks inside groups.

⏱ 2 min read▶ Video at 27:55🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Which are the two most expensive books in each genre? Row number counts rows within each group, in an order you choose. Then we keep rows one and two.

  • Each genre
  • Most expensive two
  • row_number()

Two priciest per genre

Row number over partition by genre, ordered by price descending, numbers each genre's books from one. The outer query keeps ranks one and two. Run it. The top two books in three genres.

query.sqlsql
SELECT genre, title, price
FROM (
  SELECT genre, title, price,
         row_number() OVER (PARTITION BY genre ORDER BY price DESC) AS rn
  FROM books
  WHERE genre IN ('History', 'Business', 'Thriller')
) ranked
WHERE rn <= 2
ORDER BY genre, rn;
Output
  genre   |          title           | price
----------+--------------------------+-------
 Business | The Pricing Game         | 23.99
 Business | Numbers Don't Lie        | 21.99
 History  | Empires of Salt          | 22.99
 History  | A Short History of Bread | 19.99
 Thriller | Night Train to Oslo      | 14.99
 Thriller | Deep Water               | 13.49
(6 rows)

Ranking functions

Row number never ties. Rank gives ties the same number, then skips. Dense rank gives ties the same number, with no gaps. And n tile splits rows into equal buckets.

FunctionPrices 9, 9, 7
row_number()1, 2, 3
rank()1, 1, 3
dense_rank()1, 1, 2
ntile(2)1, 1, 2

Summary

Row number, rank and dense rank number rows within groups, perfect for top N per group. Next, running totals.

Key takeaways
  • row_number
  • rank
  • dense_rank
Next up: Running Totals and LAG — looking back