Skip to main content
SQL • LESSON 169

Top N per Group

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

Advanced3 Minutes1820 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