TGViewer
SQL Programming Resources SQL Programming Resources @sqlanalyst ยท 76.7K subscribers
Post #2833 514
SQL Interview Series โ€” Part 4

๐Ÿ“Œ Question 4: Find the Highest Salary in Each Department

Suppose you have an Employee table:

Employee

โ€ข employee_id

โ€ข employee_name

โ€ข department

โ€ข salary

Example:

employee_id | employee_name | department | salary
------------|---------------|------------|-------
1 | Amit | IT | 60000
2 | Rahul | IT | 90000
3 | Priya | HR | 50000
4 | Neha | HR | 70000
5 | Raj | Finance | 85000
6 | Karan | Finance | 95000


โ“ Find the employee(s) with the highest salary in each department.

๐Ÿ’ก Approach

We need to find the maximum salary separately for every department.

A common approach is to use a window function.

"RANK()" assigns a ranking within each department.

SELECT
employee_id,
employee_name,
department,
salary
FROM (
SELECT
employee_id,
employee_name,
department,
salary,
RANK() OVER (
PARTITION BY department
ORDER BY salary DESC
) AS rnk
FROM Employee
) e
WHERE rnk = 1;


๐Ÿ”Ž How does it work?

"PARTITION BY department"

โ†’ Creates a separate ranking for each department.

"ORDER BY salary DESC"

โ†’ Places the highest salary first.

"RANK()"

โ†’ Gives the highest salary a rank of 1.

Finally:

WHERE rnk = 1

โ†’ Keeps only the highest-paid employee(s).

Expected result:

employee_name | department | salary
--------------|------------|-------
Rahul | IT | 90000
Neha | HR | 70000
Karan | Finance | 95000


โš ๏ธ Why use "RANK()"?

If two employees have the same highest salary, both will receive rank 1 and both will be returned.

For example:

IT

Rahul 90000

Amit 90000

Raj 80000

Both Rahul and Amit will be returned.

Double Tap โค๏ธ For More
  • โค 4
More from @sqlanalyst
  1. Oct 7, 2026๐Ÿš€๐—ฃ๐—ฎ๐˜† ๐—”๐—ณ๐˜๐—ฒ๐—ฟ ๐—ฃ๐—น๐—ฎ๐—ฐ๐—ฒ๐—บ๐—ฒ๐—ป๐˜ ๐—ง๐—ฟ๐—ฎ๐—ถ๐—ป๐—ถ๐—ป๐—ด | ๐—•๐—ฒ๐—ฐ๐—ผ๐—บ๐—ฒ ๐—ฎ ๐—™๐˜‚๐—น๐—น๐˜€๐˜๐—ฎ๐—ฐโ€ฆ
  2. Oct 7, 2026๐— ๐—ฎ๐˜€๐˜๐—ฒ๐—ฟ ๐—ฃ๐—ผ๐˜„๐—ฒ๐—ฟ ๐—•๐—œ ๐—ณ๐—ผ๐—ฟ ๐—™๐—ฅ๐—˜๐—˜! ๐Ÿ”ฅ Learn Power BI through these FREE learninโ€ฆ
  3. Sep 29, 2026SQL Interview Series โ€” Part 2 ๐Ÿ“Œ Question 2: Find Duplicate Records Suppose you have an Emโ€ฆ
  4. Sep 29, 2026๐—™๐—ฅ๐—˜๐—˜ ๐—ฅ๐—ฒ๐˜€๐—ผ๐˜‚๐—ฟ๐—ฐ๐—ฒ๐˜€ ๐—ง๐—ผ ๐—Ÿ๐—ฒ๐—ฎ๐—ฟ๐—ป ๐—”๐—œ ๐—ถ๐—ป ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ๐Ÿš€ โ€‹ Explore 6 free resourceโ€ฆ
  5. Sep 29, 2026SQL Interview Series โ€” Part 1 Hi guys, let's start a SQL interview series covering frequenโ€ฆ
  6. Sep 28, 2026๐Ÿง  Real-World SQL Scenario-Based Questions & Answers 1. Get the 2nd highest salary from thโ€ฆ
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 โ†’