Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BISQL languageJuniorCommonPractical

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

Solution · Second-highest distinct value
Dialect · Portable SQLRuntime · SQLite sample DB

Runs against the resettable SQLite sample database used by the playground.

SQL
SQLite · sample DB · browser sandbox
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.

#sql#ranking#window-functions#aggregation

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery