Ivy Professional School
Rating
Learning/SQL Data Drill #3

Rank & File

Last updated

Use window functions to find the second highest and third lowest earners in each department — combined into a single result table.

SQLIntermediateDENSE_RANKWindow FunctionsCTEFULL OUTER JOIN

Your Objective

Use window functions to find the second highest and third lowest earners in each department — combined into a single result table.

The Setup

Your dataset contains two tables from a company's HR database: 1. A Department table with the ID and name of each department 2. An Employee table with the ID, name, salary, joining date, and department reference for each employee

Table Schema

Department
ColumnTypeKey / Notes
idINTPK
nameVARCHAR(50)
Employee
ColumnTypeKey / Notes
idINTPK
nameVARCHAR(50)
salaryDECIMAL(10,2)
joining_dateDATE
department_idINTFK

Sample Data

Department — 8 rows

idname
1HR
2Engineering
3Marketing
4Sales
5IT
6Finance
7Graphic Designer
8Data Analyst

Employee — 20 rows

idnamesalaryjoining_datedepartment_id
1Alice70,0002020-01-151
2Bob85,0002019-03-222
3Charlie60,0002021-05-181
4David95,0002018-07-113
5Eva80,0002017-09-092
6Frank75,0002016-11-143
7Grace90,0002015-02-231
8Henry68,0002021-04-302
9Irene72,0002020-06-251
10Jack78,0002019-08-193
11Karen83,0002018-10-074
12Leo95,0002017-12-131
13Mona87,0002016-03-212
14Nick63,0002015-05-295
15Olivia77,0002014-07-151
16Peter82,0002021-01-182
17Quinn91,0002020-03-126
18Rachel88,0002019-09-281
19Steve93,0002018-11-062
20Tina76,0002017-04-163

Your Task

List the employees who have the second highest salary and the third lowest salary in their respective departments. Give the answers in a single table with the format: department_name | second_highest | third_lowest

Your output should look like this (partial example):

department_namesecond_highestthird_lowest
EngineeringMonaPeter
………

Important Notes

  • →Only include departments that have enough employees to satisfy the condition. For example, a department with only 1 employee cannot have a second highest salary.
  • →If the same employee holds both ranks (second highest and third lowest), they should appear in both columns.
  • →Use DENSE_RANK rather than ROW_NUMBER — if two employees share the same salary, they should receive the same rank.
Explore Enterprise Solutions