1. Home
  2. Interview Questions
  3. SQL
  4. How do you fetch the entire row with the highest salary in e…

Try answering first

In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.

1 Answer

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best answer ·

Short answer: You cannot do it with GROUP BY alone, because a non-aggregated column such as name is not tied to the MAX value. Use a window function like ROW_NUMBER or RANK partitioned by department, or join the table back to a grouped subquery of MAX salary per department.

Detailed explanation

This is known as the greatest-n-per-group problem. Many candidates first write:

SELECT dept_id, name, MAX(salary) FROM employees GROUP BY dept_id;

This query is wrong. The SQL standard says that every selected column must either appear in GROUP BY, be functionally dependent on the grouped columns, or sit inside an aggregate. MAX(salary) returns one value per group, but nothing tells the database which name to show alongside it.

  • PostgreSQL, SQL Server and Oracle reject the query outright.
  • MySQL with ONLY_FULL_GROUP_BY disabled (the default before 5.7) accepts it. It then returns a value from some arbitrary row in the group, which may not be the top earner. The query "works" in testing and silently gives wrong results later.

There are three correct approaches:

  1. Window function (preferred): rank the rows inside each department, then keep rank 1.
    • ROW_NUMBER returns exactly one row per group. Add a tie-breaker to ORDER BY so the result is deterministic.
    • RANK or DENSE_RANK returns every row that ties for the top salary.
    • This approach extends easily to top-3 per group.
  2. Join to an aggregated subquery: compute MAX(salary) per dept_id, then join back on both dept_id and salary. This works in databases without window functions and naturally returns ties.
  3. Correlated subquery: WHERE salary = (SELECT MAX(salary) FROM employees e2 WHERE e2.dept_id = e.dept_id). It is readable, and good optimisers handle it well, but it can be slow on old engines.

For performance on large tables, a composite index on (dept_id, salary) helps all three approaches. The engine can find each department's maximum without a full sort.

Example

-- 1. Window function: one row per department, ties broken by emp_id
SELECT emp_id, name, dept_id, salary
FROM (
  SELECT e.*,
         ROW_NUMBER() OVER (PARTITION BY dept_id
                            ORDER BY salary DESC, emp_id) AS rn
  FROM employees e
) t
WHERE rn = 1;

-- Use RANK() instead to return all employees tied at the top

-- 2. Join to grouped MAX (returns ties)
SELECT e.emp_id, e.name, e.dept_id, e.salary
FROM employees e
JOIN (
  SELECT dept_id, MAX(salary) AS max_sal
  FROM employees
  GROUP BY dept_id
) m ON m.dept_id = e.dept_id AND m.max_sal = e.salary;

-- 3. PostgreSQL-only shortcut
SELECT DISTINCT ON (dept_id) emp_id, name, dept_id, salary
FROM employees
ORDER BY dept_id, salary DESC, emp_id;

Common mistakes

  • Adding name to GROUP BY to silence the error. This creates one group per employee, and the "max" becomes each person's own salary.
  • Joining back on salary alone instead of dept_id plus salary. An employee in another department who happens to earn the same amount gets matched wrongly.
  • Using ROW_NUMBER without a tie-breaker and then wondering why a different employee appears on each run.
  • Filtering the window result with WHERE ROW_NUMBER() ... = 1 directly. Window functions are evaluated after WHERE, so you need a subquery or CTE.
  • Forgetting that departments with a NULL dept_id form their own partition, which may or may not be wanted.

Follow-up questions

  • How would you change the query to return the top 3 earners per department, including ties?
  • What is the difference between RANK and DENSE_RANK when salaries tie?
  • Why does MySQL sometimes allow selecting columns not in GROUP BY, and what does ONLY_FULL_GROUP_BY change?

Interview tip: Explain why the naive GROUP BY query is wrong before writing the window-function solution, and mention how you would handle ties. Interviewers usually probe ties next.

Reviewed by the Interview Questions editorial team · Last updated

How well did you know this?

Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.

Your Answer

More hard SQL questions

All hard questions →

Related Questions

‹
Q7 of 10 · SQL
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA