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 query to find the top three highest-paid employees in each department using window functions.

Write a query to find the top three highest-paid employees in each department using window functions.

SQLmedium2 min read

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

To find the top three highest paid employees in each department, you use a window function to rank employees within their respective departments, then filter for those ranks. The choice between DENSE…

🤖 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
Bristol Myers SquibbWipro
Key Concepts Tested
partitionwindow

Why This Question Matters

This medium-level SQL question appears frequently in data engineering interviews at companies like Bristol Myers Squibb, Wipro. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (partition, window) 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
487 wordsIncludes code

To find the top three highest-paid employees in each department, you use a window function to rank employees within their respective departments, then filter for those ranks. The choice between DENSE_RANK() and ROW_NUMBER() depends on how ties in salary should be handled.

Mechanics and Why

The core of this solution involves a window function, specifically DENSE_RANK() or ROW_NUMBER(), applied over partitions of data.
  • PARTITION BY department: This clause divides the employees into separate groups, one for each department. The ranking will then be performed independently within each of these groups.
  • ORDER BY salary DESC: Within each department partition, employees are sorted by their salary in descending order, so the highest earners receive the lowest rank numbers.
  • DENSE_RANK() vs. ROW_NUMBER():
  • * DENSE_RANK(): Assigns a rank to each row within its partition, with no gaps in the ranking sequence if there are ties. If two employees in a department have the same highest salary, they both get rank 1, and the next highest salary gets rank 2. This means you might get more than three employees if there are ties for the 3rd position. * ROW_NUMBER(): Assigns a unique, sequential integer rank to each row within its partition. If two employees have the same salary, their rank is determined by their order within the partition, which can be arbitrary unless an additional tie-breaker (e.g., employee_id) is added to the ORDER BY clause. This guarantees exactly three employees per department (unless a department has fewer than three).
  • Common Table Expression (CTE): Using a WITH clause (CTE) named ranked improves readability by first calculating the ranks and then performing the final selection and filtering.
  • Filtering: The outer SELECT statement then filters the results where the calculated rank (rn) is less than or equal to 3.
  • WITH ranked_employees AS (
        SELECT
            employee_id,
            name,
            department,
            salary,
            DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rn
        FROM
            employees
    )
    SELECT
        employee_id,
        name,
        department,
        salary
    FROM
        ranked_employees
    WHERE
        rn <= 3
    ORDER BY
        department, salary DESC;
    

    Business Nuance and Trade-offs

    The choice between DENSE_RANK() and ROW_NUMBER() is a critical business decision. If two employees tie for the third highest salary, DENSE_RANK() will include both, potentially returning four or more employees for that department. ROW_NUMBER(), conversely, will strictly return three employees per department, requiring a deterministic tie-breaker (e.g., ORDER BY salary DESC, employee_id ASC) to ensure consistent results.

    For very large datasets, PARTITION BY operations can be computationally expensive in distributed systems like Spark, as they often necessitate a full data shuffle across nodes. Data engineers should be aware of these performance implications and consider optimizing the underlying table structure (e.g., using clustering keys in Snowflake or partitioning in Delta Lake) if this query is run frequently on massive tables.

    In the interview, also mention the importance of clarifying the business requirement for tie-breaking and discussing the performance implications of window functions on large-scale data.

    ⚡
    Pro Tip

    RED FLAG: Not clarifying whether ties should count—DENSE_RANK vs ROW_NUMBER is a product decision. PRO MOVE: 'Stakeholders wanted ties included, so we use DENSE_RANK; we document that Finance can see >3 per dept when ties exist.'

    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