Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Optimizing Second-Highest Salary Query
00:00
5 left

Optimizing Second-Highest Salary Query

MediumSQL · PostgreSQL

Problem

Write a SQL query to find the second-highest salary from an employee table, and then optimize it for a dataset containing millions of rows.

Use the employees table. Treat the second-highest value as the second-highest distinct non-null salary, and ensure duplicate salaries do not affect the result. Address the indexing consideration for a large PostgreSQL table.

Output

  1. Return one row with second_highest_salary.
  2. Return no rows if fewer than two distinct non-null salaries exist.

Schema

employees
ColumnTypeDescription
employee_idPKINTEGERUnique employee identifier
employee_nameVARCHAR(100)Employee's full name
salaryNUMERIC(12,2)Employee annual salary
departmentVARCHAR(80)Employee department
Tablesemployees
Interviewer

Your question is Optimizing Second-Highest Salary Query. Start with the requirements and the one table in the Question tab.

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.
CodePostgreSQL
You need to log in / sign up to run or submit.Ln 1
Run your query to see results here.