Skip to main content

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).

Official Reference

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).

Follow-up Interview Question · When is a LATERAL subquery faster than a full-table window scan?

Module Context & References

PostgreSQL & Redis · Practice SQL & schema drills The classic SQL queries, locking patterns and optimization problems tested repeatedly
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.