Which employees will be selected as the top two highest paid employees in each department?
💡 Model Answer
The result set will contain the two employees with the highest salaries in every department. A common way to produce this list is to use a window function:
SELECT empid, ename, dept_id, salary
FROM (
SELECT e.*, ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rn
FROM employee e
) t
WHERE rn <= 2;
Here, ROW_NUMBER() assigns 1 to the highest paid employee in each department, 2 to the second highest, and so on. The outer query keeps only rows where rn is 1 or 2. This method is efficient and works in most SQL dialects. If your database lacks window functions, you could use a correlated subquery with LIMIT 2 per department, but the window approach is preferred for readability and performance.
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