Skip to main content
SQL โ€ข LESSON 169

Top N per Group

How can we find the top 3 highest-earning employees in each department?

Advancedโฑ 3 Minutesโญ 1820 XP
๐Ÿค” THE QUESTION

How can we find the top 3 highest-earning employees in each department?

๐Ÿ’ก WHAT IS IT?

Filtering a ROW_NUMBER() partition window subquery for rn <= 3 retrieves the top N records per category.

๐ŸŽฏ WHAT IS IT USED FOR?

Top 3 products per category, highest 3 sales per region, top 3 songs per artist.

๐Ÿ’ป EXAMPLE
SELECT *
FROM (
    SELECT
        name,
        department_id,
        salary,
        ROW_NUMBER() OVER (
            PARTITION BY department_id
            ORDER BY salary DESC
        ) AS rn
    FROM employees
) ranked
WHERE rn <= 3;

๐ŸŽฏ Mission Objectives

Practice typing production-grade SQL code for Top N per Group.

  • โœ“ Top N per group
  • โœ“ ROW_NUMBER <= 3
  • โœ“ Partitioned ranking subquery
  • โœ“ Analytical patterns