High-frequency SQL interview problem closely related to ROW_NUMBER(), RANK(), and DENSE_RANK() is:
π Find Top N records per group
This problem tests how well you understand window functions + PARTITION BY, not just syntax.
Letβs walk through it step by step.
π§ Problem Statement
π Find the top 2 highest-paid employees in each department.
Sample data:
Employees table columns:
- emp_name
- department
- salary
Assume some employees in a department can have the same salary.
π’ Attempt 1: Using ROW_NUMBER()
SELECT emp_name, department, salary
FROM (
SELECT emp_name,
department,
salary,
ROW_NUMBER() OVER (
PARTITION BY department
ORDER BY salary DESC
) AS rn
FROM employees
) t
WHERE rn <= 2;
π Behavior of ROW_NUMBER()
- Assigns unique numbers within each department
- Breaks ties arbitrarily
β Use this when:
- You strictly want only N rows per group
- Ties do not matter
β Problem:
Employees with the same salary may get excluded.
π Attempt 2: Using RANK()
SELECT emp_name, department, salary
FROM (
SELECT emp_name,
department,
salary,
RANK() OVER (
PARTITION BY department
ORDER BY salary DESC
) AS rnk
FROM employees
) t
WHERE rnk <= 2;
π Behavior of RANK()
- Same salary β same rank
- Skips rank numbers when duplicates exist
β Use this when:
- You want competition-style ranking
- Rank gaps are acceptable
β Problem:
You may get more than N rows and missing ranks.
π― Best Approach: Using DENSE_RANK()
SELECT emp_name, department, salary
FROM (
SELECT emp_name,
department,
salary,
DENSE_RANK() OVER (
PARTITION BY department
ORDER BY salary DESC
) AS drnk
FROM employees
) t
WHERE drnk <= 2;
β Why DENSE_RANK() is ideal here
- Handles duplicate salaries correctly
- No rank gaps
- Returns top N salary levels, not just rows
This makes DENSE_RANK() the most interview-safe solution for Top-N-per-group problems.
π Comparison Summary
| Function | Handles ties | Rank gaps | Rows returned |
|---|---|---|---|
| ROW_NUMBER() | β No | β No | Exactly N |
| RANK() | β Yes | β Yes | N or more |
| DENSE_RANK() | β Yes | β No | N or more (clean) |
π‘ Interview Rule of Thumb
- Pagination / strict limits β
ROW_NUMBER() - Leaderboard ranking β
RANK() - Top N per group / Nth highest problems β
DENSE_RANK()
π¬ Interview Question for You
How would you fetch the highest salary per department, including ties, without using subqueries?
Think window functions π
Comments (0)
No comments yet. Be the first to share your thoughts!
Leave a Comment