table is salary- col -emop_id, dept_id, salary
- using window function find the second highest salary?
📝 Answer
1. Interviewer expects
The interviewer checks whether you know window functions (partitionBy, orderBy) and whether you handle duplicate salaries (ties) correctly. Also clarify: second highest per department or for the whole company?
Telugu note: same salary ఇద్దరికి ఉంటే ఎలా handle చేస్తారో చూస్తారు.
2. Why / when it happens
In real payroll data, many employees share the same salary. The three ranking functions treat ties differently:
| emp_id | salary | row_number | rank | dense_rank |
|---|---|---|---|---|
| 1 | 90000 | 1 | 1 | 1 |
| 2 | 80000 | 2 | 2 | 2 |
| 3 | 80000 | 3 | 2 | 2 |
| 4 | 70000 | 4 | 4 | 3 |
- row_number drops one of the tied employees.
- rank leaves gaps (1, 2, 2, 4).
- dense_rank has no gaps (1, 2, 2, 3).
3. Solution
- Partition by
dept_id. - Order by
salarydescending. - Apply
dense_rank(). - Filter
rnk == 2.
Telugu note: dense_rank same salary కి same rank ఇస్తుంది, so second highest ఎప్పుడూ correct.
4. Fix in code
from pyspark.sql import SparkSession, Window
from pyspark.sql.functions import col, dense_rank
spark = SparkSession.builder.getOrCreate()
data = [(1,10,90000),(2,10,80000),(3,10,80000),
(4,10,70000),(5,20,60000),(6,20,55000),
(7,20,50000)]
cols = ["emp_id", "dept_id", "salary"]
df = spark.createDataFrame(data, cols)
w = (Window.partitionBy("dept_id")
.orderBy(col("salary").desc()))
res = (df.withColumn("rnk", dense_rank().over(w))
.filter(col("rnk") == 2))
res.orderBy("dept_id", "emp_id").show()Output:
| emp_id | dept_id | salary | rnk |
|---|---|---|---|
| 2 | 10 | 80000 | 2 |
| 3 | 10 | 80000 | 2 |
| 6 | 20 | 55000 | 2 |
Spark SQL version:
SELECT emp_id, dept_id, salary
FROM (
SELECT *,
DENSE_RANK() OVER (
PARTITION BY dept_id
ORDER BY salary DESC) AS rnk
FROM salary
) t
WHERE rnk = 2;For the whole company, remove partitionBy / PARTITION BY. Window functions cannot be used directly in WHERE, so we use a subquery.
5. Your answer
"First I'd confirm whether they want it per department or for the whole company. For per department, I create a window partitioned by dept_id and ordered by salary descending, apply dense_rank, and filter rank 2. I use dense_rank because in our payroll data two employees often had the same salary; row_number would drop one and rank leaves gaps. For the whole company, I just remove the partitionBy."