Write a SQL query to find the nth highest salary in a table.

Instruction: Using PostgreSQL and employees(salary numeric), return the nth highest distinct non-NULL salary once. Show a directly executable example for n=2 and explain ties, NULLs and fewer than n distinct salaries.

Context: This question tests the candidate's ability to apply SQL querying techniques to solve common business problems, such as identifying top earners.

Updated

Official answer

Interpret “nth highest” as the nth distinct, non-NULL salary, returned once. This PostgreSQL example uses n=2:

WITH parameters(n) AS (VALUES (2)),
ranked AS (
  SELECT salary,
         DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_rank
  FROM employees
  WHERE salary IS NOT NULL
)
SELECT DISTINCT salary
FROM ranked
WHERE salary_rank = (SELECT n FROM parameters);

For salaries [100, 100, 90, 90, 80, NULL], the result is one row containing 90. If there are fewer than n distinct non-NULL salaries, the result is empty.

DENSE_RANK assigns equal salaries the same consecutive rank. DISTINCT removes repeated copies from the final output. RANK leaves gaps after ties; ROW_NUMBER ranks employees rather than distinct salary values.

For application input, validate n as a positive integer and bind it using the driver's parameter syntax. This example uses a literal to remain directly executable; @n is not a generic parameter convention for every SQL engine.

Source

PostgreSQL: window functions.

Related Questions