TGViewer
SQL Programming Resources SQL Programming Resources @sqlanalyst ยท 76.7K subscribers
Post #2839 733
SQL Interview Series โ€” Part 6

๐Ÿ“Œ Question 6: Find the Top 2 Highest-Paid Employees in Each Department

Suppose you have:

Employee

employee_id employee_name department salary

1 Amit IT 60000

2 Rahul IT 90000

3 Priya IT 80000

4 Neha HR 70000

5 Raj HR 50000

6 Karan HR 90000

โ“ Find the top 2 highest-paid employees from each department.

๐Ÿ’ก Approach

This is a classic window

-function interview question.

We need to:

1๏ธโƒฃ Divide employees by department.

2๏ธโƒฃ Rank employees by salary within each department.

3๏ธโƒฃ Keep only employees with rank โ‰ค 2.

SQL Solution

SELECT
employee_id,
employee_name,
department,
salary
FROM (
SELECT
employee_id,
employee_name,
department,
salary,
ROW_NUMBER() OVER (
PARTITION BY department
ORDER BY salary DESC
) AS rn
FROM Employee
) e
WHERE rn <= 2;


๐Ÿ”Ž How does it work?

PARTITION BY department

Creates a separate ranking for each department.

ORDER BY salary DESC

Places the highest salary first.

ROW_NUMBER()

Assigns 1, 2, 3... within each department.

Finally:

WHERE rn <= 2

keeps the top two employees from each department.

Expected Result

employee_name department salary

Rahul IT 90000

Priya IT 80000

Karan HR 90000

Neha HR 70000

โš ๏ธ Interview Trap

What if two employees have the same salary?

For example:

Rahul 90000

Priya 90000

Amit 80000

ROW_NUMBER() will still assign unique numbers:

Rahul 1

Priya 2

Amit 3

Double Tap โค๏ธ For More
  • โค 2
More from @sqlanalyst
  1. Oct 13, 2026SQL Interview Series โ€” Part 8 ๐Ÿ“Œ Question 8: Find Customers Who Have Never Placed an Orderโ€ฆ
  2. Oct 13, 2026๐—ง๐—ข๐—ฃ ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ข๐—จ๐—ฅ๐—ฆ๐—˜๐—ฆ ๐—ง๐—ข ๐—•๐—ข๐—ข๐—ฆ๐—ง ๐—ฌ๐—ข๐—จ๐—ฅ ๐—ฆ๐—ž๐—œ๐—Ÿ๐—Ÿ๐—ฆ ๐—œ๐—ก ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ! Explorโ€ฆ
  3. Oct 12, 2026๐Ÿš€ ๐—ช๐—ต๐—ถ๐—ฐ๐—ต ๐—ง๐—ฒ๐—ฐ๐—ต ๐—ฆ๐—ธ๐—ถ๐—น๐—น ๐—ช๐—ถ๐—น๐—น ๐—ฌ๐—ผ๐˜‚ ๐— ๐—ฎ๐˜€๐˜๐—ฒ๐—ฟ ๐—ถ๐—ป ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ? Want to builโ€ฆ
  4. Oct 9, 2026SQL Interview Series โ€” Part 5 ๐Ÿ“Œ Question 5: Find Employees Who Earn More Than Their Managโ€ฆ
  5. Oct 9, 2026๐Ÿ‡ฎ๐Ÿ‡ณ ๐—š๐—ข๐—ฉ๐—˜๐—ฅ๐—ก๐— ๐—˜๐—ก๐—ง ๐—ข๐—™ ๐—œ๐—ก๐——๐—œ๐—” โ€” ๐—”๐—œ๐—–๐—ง๐—˜ ๐—œ๐—ก๐—ง๐—˜๐—ฅ๐—ก๐—ฆ๐—›๐—œ๐—ฃ๐—ฆ ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ ๐Ÿš€โ€ฆ
  6. Oct 8, 2026๐ŸŽ“ ๐— ๐—ถ๐—ฐ๐—ฟ๐—ผ๐˜€๐—ผ๐—ณ๐˜ ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ผ๐˜‚๐—ฟ๐˜€๐—ฒ๐˜€ ๐˜„๐—ถ๐˜๐—ต ๐—–๐—ฒ๐—ฟ๐˜๐—ถ๐—ณ๐—ถ๐—ฐ๐—ฎ๐˜๐—ฒ๐˜€! ๐Ÿš€๐Ÿ”ฅ Upgrโ€ฆ
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook โ†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 โ†’