TGViewer
Data Analytics Data Analytics @sqlspecialist ยท 111K subscribers
Post #2891 4.92K
๐—œ๐—ป๐˜๐—ฒ๐—ฟ๐˜ƒ๐—ถ๐—ฒ๐˜„๐—ฒ๐—ฟ:

You have 2 minutes to solve this SQL query.

Find the employees who have the highest salary in each department.

๐— ๐—ฒ: Challenge accepted! ๐Ÿ’ช

SELECT
    employee_id,
    employee_name,
    department,
    salary
FROM (
    SELECT
        employee_id,
        employee_name,
        department,
        salary,
        DENSE_RANK() OVER (
            PARTITION BY department
            ORDER BY salary DESC
        ) AS rnk
    FROM employees
) ranked
WHERE rnk = 1;


๐Ÿ’ก Explanation:

This query uses the DENSE_RANK() window function to rank employees by salary within each department.

โ€ข PARTITION BY department creates separate rankings for each department.

โ€ข ORDER BY salary DESC ranks the highest salary as 1.

โ€ข DENSE_RANK() ensures that if multiple employees have the same highest salary, they all receive Rank 1.

โ€ข The outer query filters only the employees with rnk = 1.

This question tests your knowledge of:

โœ… Window Functions

โœ… DENSE_RANK() vs RANK() vs ROW_NUMBER()

โœ… Partitioning Data

๐ŸŽฏ Output Example

Employee | Department | Salary

John | IT | 95,000

Sarah | HR | 80,000

David | Finance | 90,000

Alice | IT | 95,000

(John and Alice both appear because they share the highest salary in the IT department.)

๐Ÿš€ Whenever an interview question asks for the top N records per group, think of window functions.

DENSE_RANK(), RANK(), and ROW_NUMBER() are among the most commonly tested SQL concepts.

โค๏ธ React with โค๏ธ for more SQL interview challenges!
  • โค 16
More from @sqlspecialist
  1. Oct 8, 2026๐ŸŽ“ ๐— ๐—ถ๐—ฐ๐—ฟ๐—ผ๐˜€๐—ผ๐—ณ๐˜ ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ผ๐˜‚๐—ฟ๐˜€๐—ฒ๐˜€ ๐˜„๐—ถ๐˜๐—ต ๐—–๐—ฒ๐—ฟ๐˜๐—ถ๐—ณ๐—ถ๐—ฐ๐—ฎ๐˜๐—ฒ๐˜€! ๐Ÿš€๐Ÿ”ฅ Upgrโ€ฆ
  2. Oct 7, 2026๐Ÿ“Š Kandinsky 6.0 Video: AI-Powered Content Creation for Analysts The new Kandinsky 6.0 Vidโ€ฆ
  3. Oct 7, 2026Alternatively, depending on the Excel version and requirement, I could use functions suchโ€ฆ
  4. Oct 7, 2026๐Ÿ“Š Data Analyst Interview Series โ€” Part 5 Guys, let's continue our Data Analyst Interviewโ€ฆ
  5. Oct 7, 2026๐Ÿš€๐—ฃ๐—ฎ๐˜† ๐—”๐—ณ๐˜๐—ฒ๐—ฟ ๐—ฃ๐—น๐—ฎ๐—ฐ๐—ฒ๐—บ๐—ฒ๐—ป๐˜ ๐—ง๐—ฟ๐—ฎ๐—ถ๐—ป๐—ถ๐—ป๐—ด | ๐—•๐—ฒ๐—ฐ๐—ผ๐—บ๐—ฒ ๐—ฎ ๐—™๐˜‚๐—น๐—น๐˜€๐˜๐—ฎ๐—ฐโ€ฆ
  6. Oct 7, 2026๐Ÿ”Ÿ What is the difference between UNION and JOIN? Sample Answer: "JOIN combines columns frโ€ฆ
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 โ†’