Write SQL to return the second-highest distinct salary, score, or amount.
Answer
Rank values in descending order with DENSE_RANK and select rank two. DENSE_RANK is appropriate when equal values represent the same distinct position. A MAX value below the overall MAX is another compact solution for exactly the second distinct value, but ranking generalizes more naturally.
Strong answer includes
- treats equal values as the same rank
- uses DENSE_RANK or a correct nested MAX solution
- distinguishes distinct-value ranking from row numbering
Practical example
Dialect · Portable SQLRuntime · SQLite sample DB
Runs against the resettable SQLite sample database used by the playground.
SQL
Result
Run the query to see the result.
DENSE_RANK gives equal non-NULL values the same position without gaps, so position 2 is the second-highest distinct salary. NULL is excluded explicitly so DBMS-specific NULL ordering cannot change the answer.
Expected result: The second-highest distinct value when it exists.