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/SQL query to find the second highest salary from each department.

SQL query to find the second highest salary from each department.

SQLmedium2 min read

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

The most robust SQL approach to find the second highest salary from each department utilizes a window function, specifically DENSE RANK() , to assign a rank within each department based on salary,…

🤖 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
AccentureYash Technologies
Key Concepts Tested
partitionsqlwindow

Why This Question Matters

This medium-level SQL question appears frequently in data engineering interviews at companies like Accenture, Yash Technologies. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (partition, sql, 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
454 wordsIncludes code

The most robust SQL approach to find the second highest salary from each department utilizes a window function, specifically DENSE_RANK(), to assign a rank within each department based on salary, then filters for rank 2.

SELECT
    dept_id,
    salary
FROM (
    SELECT
        dept_id,
        salary,
        DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rk
    FROM
        employee
) AS ranked_salaries
WHERE
    rk = 2;

Mechanics and Why It Works

This query employs a subquery (or a Common Table Expression) to first calculate the rank of each employee's salary within their respective department.
PARTITION BY dept_id: This clause divides the dataset into independent groups, one for each dept_id. All subsequent window function calculations (like ranking) are performed within* these partitions, ensuring per-department analysis.
* ORDER BY salary DESC: Within each department partition, employees are ordered by their salary in descending order. This ensures that the highest salary receives rank 1.
DENSE_RANK(): This window function assigns a unique rank to each distinct salary value within a partition. If multiple employees share the highest salary, they all receive rank 1, and the next distinct* salary receives rank 2. This is crucial for "Nth highest" problems with ties; RANK() would assign rank 1 to all tied highest salaries but then skip rank 2, assigning 3 to the next distinct salary. ROW_NUMBER() would assign a unique rank to each row, even for tied salaries, which doesn't align with finding the "second highest salary tier."
* WHERE rk = 2: The outer query then filters these ranked results, selecting only those rows where the calculated rank is exactly 2, effectively giving us the second highest salary (or salaries, if tied) for each department.

Key Trade-offs and Considerations

Using window functions like DENSE_RANK() is generally the most efficient and readable SQL solution for this problem. Databases optimize these operations, often involving an internal sort per partition. For very large datasets in distributed systems (e.g., Apache Spark, Snowflake), the PARTITION BY clause can lead to data shuffling, where all data for a given dept_id must be co-located on the same processing unit. This network I/O can be a significant performance factor, especially with high data skew (one department having vastly more employees).

This solution gracefully handles edge cases: departments with fewer than two employees will simply not appear in the final result, and it correctly identifies all employees who share the second highest salary if there are ties.

In the interview, also mention…

Discuss the critical distinction between RANK(), DENSE_RANK(), and ROW_NUMBER() and why DENSE_RANK() is the most appropriate for "Nth highest" questions involving potential ties. Also, touch upon the performance characteristics of window functions, especially data shuffling in distributed environments due to PARTITION BY clauses.

⚡
Pro Tip

Red Flag: Using RANK when dept has single employee at top—'second' would be rank 2 with RANK (correct) but DENSE_RANK is safer for ties. Pro-Move: 'I use DENSE_RANK; for depts with <2 employees we get no row—I document that as expected.'

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

SQL Window Functions & CTEs: The Complete Interview Guide for Data Engineers (2026)

Window functions and CTEs are the #1 tested SQL topics at Amazon, Google, and Databricks. This guide covers every pattern you'll face with production-ready answers.

18 min read →

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