Home › Interview Questions › How would you partition by department to get the h…

How would you partition by department to get the highest paid employee in each department?

🟡 Medium Conceptual Mid level
1Times asked
Oct 2026Last seen
Oct 2026First seen

💡 Model Answer

To retrieve the highest paid employee in each department, you can use a window function with ROW_NUMBER() to rank employees within each department by salary in descending order, then filter for rank = 1. For example: SELECT dept, employee, salary FROM (SELECT dept, employee, salary, ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn FROM employees) t WHERE rn = 1; This returns one row per department, the employee with the highest salary. If you need the top N employees per department, replace rn = 1 with rn <= N. An alternative is to use a correlated subquery: SELECT e.* FROM employees e WHERE e.salary = (SELECT MAX(salary) FROM employees WHERE dept = e.dept); However, the window function approach is often more efficient, especially on large tables, because it can leverage indexes on the partition and order columns. It also handles ties gracefully if you use RANK() or DENSE_RANK() instead of ROW_NUMBER().

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500