Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Start free
Advanced Salary Ranking SQL
00:00
5 left

Advanced Salary Ranking SQL

MediumSQL · PostgreSQL

Problem

Decision Point wants to compare compensation among currently active employees. Write a PostgreSQL query that returns every active employee who earns the second highest distinct salary, along with their department.

Requirements

  1. Consider only employees whose employment_status is Active and whose salary is not NULL.
  2. Rank distinct salaries from highest to lowest using a window function. The query should be easy to adapt from the second highest salary to the Nth highest salary.
  3. Return the employee ID, employee name, department name, and salary for all employees at the selected rank.
  4. Order the output by employee ID ascending. Explain why DENSE_RANK is preferable to ROW_NUMBER when tied salaries should share a rank.

Output details

  • Name the output columns employee_id, employee_name, department_name, and salary in that order.
  • Exclude active employees whose department_id has no matching department record.

Schema

employees
ColumnTypeDescription
employee_idPKINTUnique employee identifier
employee_nameVARCHAR(100)Employee's full name
department_idINTReferences departments.department_id
salaryNUMERIC(12,2)Annual employee salary
employment_statusVARCHAR(20)Current employment status
departments
ColumnTypeDescription
department_idPKINTUnique department identifier
department_nameVARCHAR(100)Department display name
Tablesemployeesdepartments
Interviewer

Whenever you're ready, walk me through your approach or go straight to the code. The requirements and the two tables are in the Question tab.

Sign up free to run or submit. Log in
CodePostgreSQL
Sign up free to run your code. Your draft is saved.Run with a free accountLog inLn 1
Run your query to see results here.