Write an SQL query that returns the top two highest‑paid employees from each department.
1Times asked
Jul 2026Last seen
Jul 2026First seen
💡 Model Answer
Use the ROW_NUMBER() window function to rank employees within each department by salary in descending order, then filter for the first two rows per department:
sql
SELECT emp_name,
department,
salary
FROM (
SELECT emp_name,
department,
salary,
ROW_NUMBER() OVER (PARTITION BY department
ORDER BY salary DESC) AS rn
FROM Employees
) AS ranked
WHERE rn <= 2;This query has a time complexity of O(n log n) due to the sorting required for the window function, but it is efficient for typical relational databases. It handles ties by arbitrarily ordering rows with the same salary; if you need deterministic results, add a secondary order column such as emp_id.
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