Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Writing SQL for Ranking

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

Your question is Writing SQL for Ranking. 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

TCS iON is reviewing compensation among its active employees. Write a PostgreSQL query to find every active employee whose salary is the second-highest distinct salary in the employee table.

Requirements

  1. Exclude employees whose employment status is not Active before calculating the salary ranking.
  2. Treat tied salaries as one salary level, so all employees at the second-highest distinct salary must be returned.
  3. Include each employee's name, salary, department name, and calculated salary rank.
  4. Preserve employees even if their department reference is missing, and sort the result by salary descending and employee name ascending.

Schema

employees
ColumnTypeDescription
employee_idPKINTEGERUnique employee identifier
employee_nameVARCHAR(100)Employee's full name
salaryNUMERIC(12,2)Annual salary
department_idINTEGERReference to the employee's department
employment_statusVARCHAR(20)Current employment status
departments
ColumnTypeDescription
department_idPKINTEGERUnique department identifier
department_nameVARCHAR(100)Department name
Tablesemployeesdepartments
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results