Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Trending in AI
Hot
Agentic AI EngineerForward-Deployed EngineerGenAI EngineerAI Architect
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
3rd Highest Value Logic
00:00
5 left

3rd Highest Value Logic

MediumSQL · PostgreSQL

Problem

Write logic to get the 3rd highest salary using SQL and PySpark, and if there are fewer than 3 values, take the second one.

Use the employee compensation records joined to employees. Treat salaries as distinct, ignore NULL salaries, and return the highest available salary if only one distinct value exists.

Output

  1. Return one row with one column, selected_salary.
  2. Return the third-highest distinct salary when at least three exist; otherwise return the second-highest, or the only available salary.
  3. The result contains no additional rows or columns.

Schema

employees
ColumnTypeDescription
employee_idPKINTUnique employee identifier
employee_nameVARCHAR(100)Employee full name
departmentVARCHAR(80)Employee department
employee_compensation
ColumnTypeDescription
compensation_idPKINTUnique compensation record identifier
employee_idINTReferenced employee identifier
salaryNUMERIC(12,2)Annual salary amount
Tablesemployeesemployee_compensation
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.