Top N per Group: Highest Paid in Each Department

SQL Interview Problems: 12 Classic Questions Solved · Ranking and Top Rows · 6 min read · Updated

Top earner in each department

  1. Start with all employees. GROUP BY alone would hide the names.
  2. PARTITION BY splits the rows into one group for each department without removing any row.
  3. Inside each group the people are ranked from the highest salary down.
  4. A WITH query lets the next step filter on the rank.
  5. You get the person and the salary for each department, and ties appear together.

"Show the highest paid employee in each department" is the most asked group problem. The reason is simple: a plain GROUP BY can give you the highest salary of each department, but not the name of the person who earns it. As soon as you add the name to the SELECT, you must either group by it as well, which breaks the grouping, or find another way. This lesson shows the two good ways, and what to do when two people tie.

Why GROUP BY alone is not enough

SELECT dept_id, MAX(salary) FROM employees GROUP BY dept_id works and gives one row per department. But the moment you also select name, the database does not know which of the department's names to show. Some engines refuse the query, and some, like older MySQL, return an arbitrary name that may not belong to the highest salary. That wrong answer looks right, which is the dangerous part.

Way 1: a window function with PARTITION BY

A window function looks at the other rows without collapsing them. PARTITION BY dept_id makes a separate group for each department, and ORDER BY salary DESC ranks the people inside it. Then you keep the rows with rank 1. The ranking cannot be filtered in the same level, so the ranking goes into a common table expression, written with WITH.

WITH r AS (
  SELECT d.name AS dept, e.name, e.salary,
         RANK() OVER (PARTITION BY e.dept_id ORDER BY e.salary DESC) AS rnk
  FROM employees e
  JOIN departments d ON d.id = e.dept_id
  WHERE e.salary IS NOT NULL
)
SELECT dept, name, salary
FROM r
WHERE rnk = 1
ORDER BY dept;
dept        | name        | salary
Engineering | Meera Joshi | 150000
Finance     | Dev Patel   | 100000
HR          | Ravi Menon  | 90000
Sales       | Omar Ali    | 110000

Each department appears once with its top earner. Jack Reed's missing salary is removed in the inner query, so Finance shows Dev Patel with 100000 and not a NULL. We used RANK, so if two people tied for first place both would be shown, which is usually what you want for "who earns the most".

Top two or top three per group

Change the condition to rnk <= 2. Now the choice between the ranking functions matters. With DENSE_RANK Sales shows three people: Omar at rank 1 and both Priya and Tom at rank 2, because they tie at 70000.

WITH r AS (
  SELECT d.name AS dept, e.name, e.salary,
         DENSE_RANK() OVER (PARTITION BY e.dept_id ORDER BY e.salary DESC) AS rnk
  FROM employees e
  JOIN departments d ON d.id = e.dept_id
  WHERE e.salary IS NOT NULL
)
SELECT dept, name, salary, rnk
FROM r
WHERE rnk <= 2
ORDER BY dept, rnk, name;
dept        | name        | salary | rnk
Engineering | Meera Joshi | 150000 | 1
Engineering | Nia Okoye   | 130000 | 2
Finance     | Dev Patel   | 100000 | 1
Finance     | Chloe Wu    | 72000  | 2
HR          | Ravi Menon  | 90000  | 1
HR          | Ella Stone  | 55000  | 2
Sales       | Omar Ali    | 110000 | 1
Sales       | Priya Nair  | 70000  | 2
Sales       | Tom Hill    | 70000  | 2

With ROW_NUMBER you would get exactly two rows per department and one of the tied people would silently disappear. With RANK the tied people at rank 2 would still both show, but a person after a tie would jump to rank 4. Tell the interviewer which behaviour you picked: "I used DENSE_RANK, so ties at the second level are all included." If they want exactly N rows per group, then say ROW_NUMBER with a clear tie-breaker such as the earlier hire date.

Way 2: a correlated subquery

If window functions are not allowed, or you want to show you know the older way, ask for the rows whose salary equals the maximum of their own department. The inner query refers to the outer row, which is why it is called correlated.

SELECT e.name, e.dept_id, e.salary
FROM employees e
WHERE e.salary = (
  SELECT MAX(salary) FROM employees WHERE dept_id = e.dept_id
)
ORDER BY e.dept_id, e.name;
name        | dept_id | salary
Meera Joshi | 1       | 150000
Omar Ali    | 2       | 110000
Ravi Menon  | 3       | 90000
Dev Patel   | 4       | 100000

It returns the same four people. It is easy to read, but the database may run the inner query once per row, which can be slow on large tables. That is a good point to mention: window functions usually scan the data once.

Join the table to a small summary of the department averages, then compare. This shape, a subquery in FROM used as a table, appears in many interviews.

SELECT e.name, d.name AS dept, e.salary, ROUND(a.avg_salary) AS dept_avg
FROM employees e
JOIN departments d ON d.id = e.dept_id
JOIN (
  SELECT dept_id, AVG(salary) AS avg_salary
  FROM employees
  GROUP BY dept_id
) a ON a.dept_id = e.dept_id
WHERE e.salary > a.avg_salary
ORDER BY d.name, e.salary DESC;
name        | dept        | salary | dept_avg
Meera Joshi | Engineering | 150000 | 123000
Nia Okoye   | Engineering | 130000 | 123000
Dev Patel   | Finance     | 100000 | 86000
Ravi Menon  | HR          | 90000  | 72500
Omar Ali    | Sales       | 110000 | 78750

Look at Finance. The average is 86000, which is the average of 100000 and 72000 only. Jack Reed's missing salary is ignored by AVG, not counted as zero. This is correct behaviour, and it is worth saying aloud, because the other choice would give 57333 and change who is above average. Lesson 11 returns to this.

Common mistakes

  • Selecting a non-grouped column next to MAX and trusting the result.
  • Using ROW_NUMBER and losing tied people without noticing.
  • Filtering on the rank in the same SELECT where it is created. Wrap it in a WITH query or a subquery.
  • Forgetting PARTITION BY, which ranks everyone in the company together.

Your task

  1. Show the lowest paid person in each department. Decide what you do about Jack Reed.
  2. Show the top three distinct salaries in each department with DENSE_RANK. How many rows does Sales return?
  3. Return exactly one person per department, using ROW_NUMBER and the earlier hire date as the tie-breaker.
  4. Show everyone paid below their department average, with the average rounded.

How to check it worked

  • The top paid person in Engineering is Meera Joshi with 150000.
  • With DENSE_RANK and rank 2 or lower, Sales returns three people.
  • Your one-per-department query returns exactly four rows, because Legal has no employees.

Frequently asked questions

Should I use ROW_NUMBER, RANK or DENSE_RANK?

Use ROW_NUMBER when you need exactly N rows per group. Use RANK or DENSE_RANK when tied people should all appear. Say which one you chose.

Can I do this without window functions?

Yes. A correlated subquery that compares each salary with the department maximum works in every database, though it can be slower on big tables.

Why does the department Legal not appear?

It has no employees, so there is no row to rank. An inner join or a window query only sees rows that exist. Lesson 5 shows how to keep empty groups.