HomeInterview QuestionsWrite an SQL query that finds the employee(s) who …

Write an SQL query that finds the employee(s) who earn the maximum salary in each department.

🟡 Medium Coding Junior level
1Times asked
Jul 2026Last seen
Jul 2026First seen

💡 Model Answer

A straightforward approach is to use a correlated subquery that compares each employee’s salary to the maximum salary in their department:

sql
SELECT e.emp_name,
       e.department,
       e.salary
FROM   Employees e
WHERE  e.salary = (
        SELECT MAX(salary)
        FROM   Employees
        WHERE  department = e.department
       );

Alternatively, you can use a window function:

sql
SELECT emp_name,
       department,
       salary
FROM   (
        SELECT emp_name,
               department,
               salary,
               MAX(salary) OVER (PARTITION BY department) AS max_sal
        FROM   Employees
       ) AS t
WHERE  salary = max_sal;

Both queries run in O(n) time with a single scan of the table, making them efficient for large datasets.

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