Top-N per group (e.g. top 3 earners per department)
Write a SQL query returning the top 3 highest-paid employees in each department (handling ties explicitly).
Model Answer & Explanation
WITH ranked AS (
SELECT id, department_id, name, salary,
DENSE_RANK() OVER (
PARTITION BY department_id ORDER BY salary DESC
) AS rnk
FROM employees
)
SELECT department_id, name, salary
FROM ranked
WHERE rnk <= 3; Use a CTE or subquery with DENSE_RANK() (for top 3 distinct salaries) or ROW_NUMBER() (for strictly 3 rows) partitioned by department_id and ordered by salary DESC, then filter rank <= 3 in the outer query. In Postgres, LATERAL join with LIMIT 3 also shines when backed by an index on (department_id, salary DESC).