Ivy Professional School
Rating
Learning/SQL Data Drill #13

Department-wise Salary Ranking

Last updated

Identify the employees with the second highest salary and third lowest salary in each department using SQL ranking functions.

SQLIntermediateWindow FunctionsDENSE_RANKCTEINNER JOINSalary Analysis

Your Objective

Identify the employees with the second highest salary and third lowest salary in each department using SQL ranking functions.

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 Analyze department-wise salary rankings and identify specific salary positions within each department.

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
1Alice700002020-01-151
2Bob850002019-03-222
3Charlie600002021-05-181
4David950002018-07-113
5Eva800002017-09-092
6Frank750002016-11-143
7Grace900002015-02-231
8Henry680002021-04-302
9Irene720002020-06-251
10Jack780002019-08-193
11Karen830002018-10-074
12Leo950002017-12-131
13Mona870002016-03-212
14Nick630002015-05-295
15Olivia770002014-07-151
16Peter820002021-01-182
17Quinn910002020-03-126
18Rachel880002019-09-281
19Steve930002018-11-062
20Tina760002017-04-163

Your Task

Department-wise Salary Ranking: Which employees have the second highest salary and third lowest salary in their respective departments? The final result table should have department_name, second_highest, and third_lowest columns.

Your output should look like this (partial example):

department_namesecond_highestthird_lowest
EngineeringMonaPeter
HRGraceIrene
MarketingJackJack

Before You Solve

  • →Create one CTE to rank salaries from highest to lowest within each department.
  • →Create another CTE to rank salaries from lowest to highest within each department.
  • →Use DENSE_RANK() with PARTITION BY department so ranking restarts for every department.
  • →Join both ranked CTEs on department name, then filter rank_desc = 2 and rank_asc = 3.
Explore Enterprise Solutions