Trying to find the second largest value in a column (postgres sql)

diesel picture diesel · Feb 6, 2011 · Viewed 14.7k times · Source

I am trying to find the second largest value in a column and only the second largest value.

select a.name, max(a.word) as word
from apple a
where a.word < (select max(a.word) from apple a)
group by a.name;

For some reason, what I have now returns the second largest value AND all the lower values also but fortunately avoids the largest value.

Is there a way to fix this?

Answer

seb picture seb · Apr 4, 2011

Here's another conceptually simple solution that's been running for me in .1 milliseconds on a table of 21 million rows, according to EXPLAIN ANALYZE. It returns nothing in the case where there's only one value.

SELECT a.name, 
(SELECT word FROM apple ap WHERE ap.name=a.name ORDER BY word ASC OFFSET 1 LIMIT 1) 
FROM apple a

Note that my table already had existing indices on name, word, and (name, word), which allows me to use ORDER BY like that.