Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Second Highest Salary SQL

MediumSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is Second Highest Salary SQL. Start with the requirements and the two tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Tech Mahindra's workforce analytics dashboard needs to identify the second-highest salary in each department. Write a PostgreSQL query that handles employees with missing salary values and does not treat duplicate salaries as different rank positions.

Requirements

  1. Join employees to departments and return the department name with its second-highest distinct, non-null salary.
  2. Exclude employees whose salary is NULL before ranking.
  3. Use a ranking approach where employees with the same salary share the same position.
  4. Return one row per department that has at least two distinct non-null salary values, ordered alphabetically by department name.

Schema

departments
ColumnTypeDescription
department_idPKINTUnique department identifier
department_nameVARCHAR(100)Name of the department
employees
ColumnTypeDescription
employee_idPKINTUnique employee identifier
employee_nameVARCHAR(100)Employee's full name
department_idINTReferences departments.department_id
salaryNUMERIC(12,2)Annual employee salary
Tablesemployeesdepartments
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results