- Home
- Interview Questions
- SQL
- 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
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:
- Window function (preferred): rank the rows inside each department, then keep rank 1.
ROW_NUMBERreturns exactly one row per group. Add a tie-breaker to ORDER BY so the result is deterministic.RANKorDENSE_RANKreturns every row that ties for the top salary.- This approach extends easily to top-3 per group.
- 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.
- 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
nameto 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() ... = 1directly. 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
Related Questions
- What is the difference between a view and a materialized view, and when would you use each? · SQL · 1 ans
- What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column) in SQL? · SQL · 1 ans
- How does a recursive CTE execute step by step, and how do you stop it looping forever? · SQL · 1 ans
- Why can wrapping an indexed column in a function in WHERE make a query slow? · SQL · 1 ans
- Why does WHERE column = NULL return no rows, and how should you filter NULLs correctly? · SQL · 1 ans
- What are insertion, update and deletion anomalies, and how does normalization prevent them? · SQL · 1 ans
- How does BCNF differ from 3NF, and why can BCNF decomposition lose a dependency? · SQL · 1 ans
- How do ON DELETE CASCADE, SET NULL and RESTRICT work, and when are cascades dangerous? · SQL · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)