How do I find the second-highest distinct value with a subquery?
Quick answer
In SQLite, select distinct scores in a subquery, sort them from highest to lowest, then skip the first and take one. For example, with scores 100, 100, 92, and 85, the query returns 92. Filtering out NULL excludes missing scores from the values being ranked. If fewer than two eligible distinct scores exist, the query returns no row. [S1]
The question, the details, the next step.
A practical checklist
Confirm the table and column names.
Keep DISTINCT so tied scores count once.
Sort descending to put the highest value first.
Use LIMIT 1 OFFSET 1 to select the next distinct value.
Decide whether NULL scores should be excluded.
Consider what to do when there is no second value.
A few more useful answers
Does this return every row tied for second place?
No. It returns the second-highest distinct score value once. To retrieve original rows with that value, use a separate query that filters rows by the value returned here.
What does the query return if there is only one distinct non-NULL score?
With the shown filter, the inner query has no second value, so the outer query returns no rows. A scalar-subquery form instead returns one row with a NULL value when its inner query returns no rows. [S2]
Sources
References used for this guide.
- [S1] SQLite SELECT: sorting and limiting query results sqlite.org · Checked
- [S2] SQLite SQL Language Expressions: subquery expressions sqlite.org · Checked
