Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/SQL/Write a SQL query to find top 3 earners in each department.

Write a SQL query to find top 3 earners in each department.

SQLmedium2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

To find the top 3 earners in each department, use a SQL window function with ROW NUMBER() or DENSE RANK() partitioned by department, then filter the results. ROW NUMBER() ensures exactly three…

🤖 Analyze Your Answer
Frequency
Low
Asked at 2 companies
Category
487
questions in SQL
Difficulty Split
130E|271M|86H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
FedEx DataworksIncedo
Key Concepts Tested
partitionsql

Why This Question Matters

This medium-level SQL question appears frequently in data engineering interviews at companies like FedEx Dataworks, Incedo. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (partition, sql) will help you answer variations of this question confidently.

How to Approach This

Break this problem into components. Identify the core trade-offs involved, then walk the interviewer through your reasoning step by step. Demonstrate awareness of edge cases and production considerations - this is what separates good answers from great ones. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
473 wordsIncludes code

To find the top 3 earners in each department, use a SQL window function with ROW_NUMBER() or DENSE_RANK() partitioned by department, then filter the results. ROW_NUMBER() ensures exactly three employees per department, while DENSE_RANK() includes all employees tied for the 3rd position, potentially returning more than three.

Mechanics and Why

The core of this solution leverages SQL window functions, specifically ROW_NUMBER() or DENSE_RANK(), combined with PARTITION BY and ORDER BY.
* PARTITION BY department: This clause divides the dataset into independent groups, with one partition for each unique department. The ranking function then operates independently within these groups.
* ORDER BY salary DESC: Within each department partition, employees are sorted by their salary in descending order, ensuring that the highest earners receive the lowest ranks.
* ROW_NUMBER(): Assigns a unique, sequential integer rank to each row within its partition. If multiple employees have the same salary, they will receive distinct ranks (e.g., 1, 2, 3) based on their physical order or additional tie-breaking columns in the ORDER BY clause. This guarantees exactly N rows per partition.
* DENSE_RANK(): Assigns ranks without gaps, and employees with identical values in the ORDER BY clause receive the same rank. For instance, if two employees tie for the 2nd highest salary, both would receive rank 2, and the next distinct salary would receive rank 3. This is preferred when business logic dictates including all tied earners.

A Common Table Expression (CTE), like ranked_employees, enhances readability by clearly separating the ranking logic from the final selection and filtering step.

WITH ranked_employees AS (
    SELECT
        employee_id,
        name,
        department,
        salary,
        ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn
    FROM
        employees
)
SELECT
    employee_id,
    name,
    department,
    salary
FROM
    ranked_employees
WHERE
    rn <= 3;

Key Trade-offs and Scalability

The primary trade-off lies in choosing between ROW_NUMBER() and DENSE_RANK(), which depends entirely on the business requirement for handling ties at the Nth position.

From a scalability perspective, PARTITION BY operations can be resource-intensive, especially on large datasets. In distributed systems like Apache Spark or cloud data warehouses such as Snowflake, partitioning typically involves a "shuffle" operation where data is redistributed across nodes based on the partitioning key (department). This data movement can be a significant performance bottleneck. The ORDER BY clause within each partition also necessitates an in-memory or disk-based sort.

To optimize performance, ensure the underlying table is structured efficiently. In traditional relational databases, an index on (department, salary DESC) can dramatically speed up both the partitioning and sorting steps. In columnar data warehouses like Snowflake, defining department as a clustering key can co-locate related data within micro-partitions, reducing scan times and improving sort efficiency.

In the interview, also mention the importance of clarifying the tie-breaking rule (i.e., ROW_NUMBER vs. DENSE_RANK) with the interviewer, as it demonstrates an understanding of business requirements and edge cases.

⚡
Pro Tip

RED FLAG: Using ORDER BY salary DESC NULLS LAST without defining tiebreaker—NULLs or ties can produce non-deterministic ordering. PRO MOVE: 'We use ROW_NUMBER(... ORDER BY salary DESC, employee_id) so ties are deterministic and our downstream reports are reproducible.'

Want all answers as a PDF for offline study?
Seven focused volumes with 750+ in-depth answers — Answer Vault →

Related SQL Questions

mediumWrite an SQL query to find the second-highest salary from an employee table.FreemediumDemonstrate the difference between DENSE_RANK() and RANK()FreemediumDiscuss differences between ROW_NUMBER(), RANK(), and DENSE_RANK(), and provide examples from your projects.FreemediumExplain the differences between Data Warehouse, Data Lake, and Delta LakeFreemediumExplain the differences between Repartition and Coalesce. When would you use each?Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning →

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked SQL interview questions, reported at 2 companies. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore SQL questions →
Categories
All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
By Company
AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
Interview Guides
All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
Products
AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer