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/Spark/Big Data/Write the PySpark code to find the second highest salary in each department.

Write the PySpark code to find the second highest salary in each department.

Spark/Big Datamedium2 min read

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

To find the second highest salary in each department using PySpark, the most robust and idiomatic approach leverages window functions. Specifically, you partition the data by department, order it by…

🤖 Analyze Your Answer
Frequency
Low
Asked at 2 companies
Category
452
questions in Spark/Big Data
Difficulty Split
88E|81M|283H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
AltimetrikInfosys
Key Concepts Tested
partitionsparksqlwindow

Why This Question Matters

This medium-level Spark/Big Data question appears frequently in data engineering interviews at companies like Altimetrik, Infosys. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (partition, spark, 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
425 wordsIncludes code

To find the second highest salary in each department using PySpark, the most robust and idiomatic approach leverages window functions. Specifically, you partition the data by department, order it by salary in descending order, and then apply dense_rank() to assign ranks within each department group, finally filtering for rank 2.

Mechanics and Why DENSE_RANK

The Window.partitionBy("department") clause logically groups rows by department. This operation necessitates a data shuffle across the Spark cluster, where all records for a given department are moved to the same executor partition. Within each department partition, orderBy(F.desc("salary")) sorts the employees by salary from highest to lowest.

F.dense_rank().over(windowSpec) then assigns a rank to each employee within their department. DENSE_RANK is crucial here because it assigns consecutive ranks without gaps, even if there are ties. For example, if two employees share the highest salary (rank 1), the next distinct salary will correctly receive rank 2. This ensures you truly find the second highest salary, not just the second row after ordering. The final step, filter(F.col("rank") == 2), isolates the employees holding the second highest salary in their respective departments.

from pyspark.sql.window import Window
from pyspark.sql import functions as F

# Assume 'df' is your DataFrame with 'department' and 'salary' columns
windowSpec = Window.partitionBy("department").orderBy(F.desc("salary"))
ranked_df = df.withColumn("rank", F.dense_rank().over(windowSpec))
result_df = ranked_df.filter(F.col("rank") == 2).select("department", "salary")

Scalability and Performance Considerations

The partitionBy operation is a full data shuffle, which can be computationally expensive due to network I/O and serialization/deserialization across Spark executors. For very large datasets, especially with highly skewed department sizes (e.g., one department with millions of employees and others with hundreds), this can lead to data skew. Skew causes a few Spark tasks to process disproportionately more data, becoming bottlenecks and slowing down the entire job.

To mitigate this:
* Data Layout: If department is a frequent partitioning key, consider physically partitioning your data lake tables (e.g., Parquet or Delta Lake) by department. This can reduce shuffle costs for subsequent queries. For systems like Databricks Delta Lake or Snowflake, Z-ORDER or clustering on department can also improve performance by co-locating related data.
Pre-filtering: If you only need to analyze a subset of departments, filter the DataFrame before* applying the window function to reduce the volume of data being shuffled.

In the interview, also mention…

Discuss the importance of understanding the Spark execution plan (DAG, stages, tasks) and how shuffles impact performance. Briefly mention that while other methods like self-joins or UDFs exist, window functions are generally the most performant and idiomatic for this type of problem in Spark.

⚡
Pro Tip

Red Flag: Using ROW_NUMBER when ties exist—you'll miss valid second-highest. Pro-Move: 'I use DENSE_RANK and add a tiebreaker (e.g., emp_id) in orderBy for deterministic results; I partition the source table by department for efficient windows.'

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

Related Spark/Big Data Questions

mediumWhat is the difference between repartition and coalesce in Apache Spark?FreehardWhat is the difference between SparkSession and SparkContext in Spark?FreemediumWhat is the difference between cache() and persist() in Spark? When would you use each?FreemediumWhat is the difference between groupByKey and reduceByKey in Spark?FreemediumWhat is the difference between narrow and wide transformations in Apache Spark? Explain with examples.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 Spark/Big Data 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 Spark/Big Data 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