Reading history

Top N Per Group in SQL

5 min read 0 views

Get the top N rows in each group in SQL with ROW_NUMBER, RANK and DENSE_RANK: best students per department, ties, and the latest row per customer.

“The top two students in each department.” “The best-selling product in each category.” “Each customer’s most recent order.” These are all the same problem: top N per group. LIMIT cannot solve it because it works on the whole result, not on each group. The standard answer is to number the rows inside each group with a ranking window function, then keep the first N.

In this lesson you will learn

  • Why LIMIT and GROUP BY alone cannot do it
  • The ROW_NUMBER + CTE pattern
  • How ROW_NUMBER, RANK and DENSE_RANK handle ties
  • Keeping or breaking ties on purpose
  • The named WINDOW clause

You should know window functions and CTEs.

The Pattern

-- Top 2 students by CGPA in each department
WITH ranked AS (
  SELECT name, dept, cgpa,
         ROW_NUMBER() OVER (PARTITION BY dept ORDER BY cgpa DESC) AS rn
  FROM students
  WHERE cgpa IS NOT NULL
)
SELECT dept, name, cgpa, rn
FROM ranked
WHERE rn <= 2
ORDER BY dept, rn;

Output

+------+--------+------+----+
| dept | name   | cgpa | rn |
+------+--------+------+----+
| BBA  | Sabbir | 3.55 | 1  |
| BBA  | Imran  | 3.1  | 2  |
| CSE  | Tania  | 3.95 | 1  |
| CSE  | Nusrat | 3.82 | 2  |
| EEE  | Arif   | 3.41 | 1  |
| EEE  | Rafi   | 2.98 | 2  |
+------+--------+------+----+
(6 rows)
  1. PARTITION BY dept splits the students into departments.
  2. ORDER BY cgpa DESC sorts each department from best to worst, and ROW_NUMBER() numbers them 1, 2, 3 …
  3. The outer query keeps rows numbered 1 or 2.

The filter must go in the outer query. You cannot write WHERE rn <= 2 in the same SELECT that creates rn, because WHERE runs before window functions are computed. Nadia’s NULL CGPA is excluded first so it cannot take a place.

Handling Ties

CREATE TABLE scores (player TEXT, team TEXT, points INTEGER);
INSERT INTO scores VALUES
 ('Rakib','Tigers',30),('Sohan','Tigers',30),('Fahim','Tigers',25),('Liton','Tigers',20),
 ('Anis','Eagles',28),('Babu','Eagles',22),('Kamal','Eagles',22);

SELECT team, player, points,
       ROW_NUMBER() OVER w AS row_num,
       RANK()       OVER w AS rnk,
       DENSE_RANK() OVER w AS dense_rnk
FROM scores
WINDOW w AS (PARTITION BY team ORDER BY points DESC)
ORDER BY team DESC, points DESC, player;

-- Best player(s) per team, keeping ties
SELECT team, player, points
FROM (SELECT *, RANK() OVER (PARTITION BY team ORDER BY points DESC) AS rnk FROM scores)
WHERE rnk = 1
ORDER BY team DESC, player;

Output

+--------+--------+--------+---------+-----+-----------+
| team   | player | points | row_num | rnk | dense_rnk |
+--------+--------+--------+---------+-----+-----------+
| Tigers | Rakib  | 30     | 1       | 1   | 1         |
| Tigers | Sohan  | 30     | 2       | 1   | 1         |
| Tigers | Fahim  | 25     | 3       | 3   | 2         |
| Tigers | Liton  | 20     | 4       | 4   | 3         |
| Eagles | Anis   | 28     | 1       | 1   | 1         |
| Eagles | Babu   | 22     | 2       | 2   | 2         |
| Eagles | Kamal  | 22     | 3       | 2   | 2         |
+--------+--------+--------+---------+-----+-----------+
(7 rows)

+--------+--------+--------+
| team   | player | points |
+--------+--------+--------+
| Tigers | Rakib  | 30     |
| Tigers | Sohan  | 30     |
| Eagles | Anis   | 28     |
+--------+--------+--------+
(3 rows)
FunctionTiesNext number after a tie
ROW_NUMBERGet different numbers (order among them is arbitrary)Continues: 1, 2, 3
RANKShare a numberSkips: 1, 1, 3
DENSE_RANKShare a numberNo gap: 1, 1, 2
  • Rakib and Sohan both scored 30. ROW_NUMBER still makes one of them 1 and the other 2; which one is not guaranteed.
  • Filtering on RANK() = 1 keeps both joint winners, so the Tigers have two “best players”.
  • WINDOW w AS (…) defines the window once and reuses it, keeping long queries tidy.

Which to use?

Exactly N rows per group: ROW_NUMBER with a tie-breaker, such as ORDER BY points DESC, player. Everyone who reaches the top N positions, including ties: RANK. The top N distinct values: DENSE_RANK.

Latest Row Per Group

“Each customer’s most recent order” is top 1 per group ordered by date:

SELECT customer, order_date, amount
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY customer
                                   ORDER BY order_date DESC) AS rn
      FROM orders)
WHERE rn = 1;

Common Mistakes

  1. Using LIMIT 2, which returns two rows in total, not two per group.
  2. Putting the filter in the same query level as the window function.
  3. No tie-breaker with ROW_NUMBER. Results can change between runs.
  4. Using MAX() with GROUP BY and expecting the other columns of that row. Standard SQL does not guarantee which row the other columns come from.

Practice Exercises

Exercise 1. Find the top scorer in each course, keeping ties, with the course title and student name.

Show answer
SELECT title, name, marks
FROM (SELECT c.title, s.name, e.marks,
             RANK() OVER (PARTITION BY c.id ORDER BY e.marks DESC) AS r
      FROM enrollments AS e
      JOIN students AS s ON s.id = e.student_id
      JOIN courses  AS c ON c.id = e.course_id)
WHERE r = 1
ORDER BY title;

Circuit Theory: Arif 81; Data Structures: Tania 95; Databases: Nusrat 92; Marketing: Sabbir 85.

Exercise 2. In scores, which players would DENSE_RANK() <= 2 return for the Eagles?

Show answer

Anis (28), Babu (22) and Kamal (22): three players, because Babu and Kamal share second place.

Frequently Asked Questions

Is there a shortcut in some databases?

Yes. PostgreSQL has DISTINCT ON (dept) for the top 1 per group, and some databases support a QUALIFY clause that filters window results directly. The ROW_NUMBER pattern works everywhere.

How do I do this without window functions?

Use a correlated subquery: keep a row if fewer than N rows in the same group have a higher value. It is correct but slower on large tables.

Summary

  • Number rows inside each group with a ranking function, then filter in an outer query.
  • ROW_NUMBER gives exactly N rows; add a tie-breaker.
  • RANK keeps ties and skips numbers; DENSE_RANK keeps ties without gaps.
  • The same pattern finds the latest or earliest row per group.

Next: Pivot Rows to Columns in SQL.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *