Java and Spring Level 2 This level · 68 of 84
Medium java spring

Two employees tie for top salary; second highest via ORDER BY salary DESC LIMIT 1 OFFSET 1?

The 30 second answer

You get the other top-tied row again, not the second-highest distinct salary. Use distinct salaries with limit and offset, or a subquery for the max below the overall max, or dense rank equals two over salary descending, which also returns every employee at that salary. If there is no second distinct value, the result is empty or null.

Could you say this in an interview?

Returns the top salary again (the second tied row), not the second-highest distinct value. Fix: SELECT DISTINCT salary … ORDER BY salary DESC LIMIT 1 OFFSET 1, or SELECT MAX(salary) FROM emp WHERE salary < (SELECT MAX(salary) FROM emp), or DENSE_RANK() OVER (ORDER BY salary DESC) = 2 (also returns all employees with that salary). Edge: no second value → empty/NULL.

SELECT DISTINCT salary FROM emp ORDER BY salary DESC LIMIT 1 OFFSET 1;

SELECT MAX(salary) FROM emp
 WHERE salary < (SELECT MAX(salary) FROM emp);

SELECT * FROM (
  SELECT *, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM emp
) t WHERE rnk = 2;

Alternate interview scenarios

"Find the top 5 customers by revenue in each region."

This is the per-group version of the same problem. LIMIT works on the whole result, so I rank inside each region with a window function instead: sum revenue per customer, then use ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) and keep rank 5 or lower. The choice of function decides how ties behave. ROW_NUMBER always returns exactly five rows. RANK and DENSE_RANK return everyone tied at the cutoff, so a region can return more than five rows.

SELECT * FROM (
  SELECT region, customer_id, SUM(amount) AS revenue,
         ROW_NUMBER() OVER (PARTITION BY region ORDER BY SUM(amount) DESC) AS rn
  FROM orders GROUP BY region, customer_id
) t WHERE rn <= 5;

"Find the Kth highest salary, ignoring duplicates."

"Ignoring duplicates" means I rank distinct salary values, so the two clean answers are DISTINCT with an offset of k minus 1, or DENSE_RANK() = k. I use DENSE_RANK, not RANK, because RANK leaves gaps after ties. With salaries 300, 300 and 200, RANK gives 200 rank 3 while DENSE_RANK gives it rank 2. I wrap the query in a scalar subquery so it returns NULL instead of no rows when there are fewer than k distinct salaries, which is the edge case interviewers check.

-- k = 3
SELECT (SELECT DISTINCT salary FROM emp
        ORDER BY salary DESC
        OFFSET 3 - 1 LIMIT 1) AS kth_salary;

SELECT DISTINCT salary FROM (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM emp
) t WHERE rnk = 3;

Sources (3)
  1. PostgreSQL — Window functions (dense_rank)postgresql.org
  2. PostgreSQL — LIMIT and OFFSETpostgresql.org
  3. PostgreSQL 17 tutorial: Window functions (PARTITION BY)postgresql.org
Previous
Next