views:

228

answers:

11

how do i retrieve the second highest value from the table

+4  A: 

In mysql you could for instance use LIMIT 1, 1:

SELECT col FROM tbl ORDER BY col DESC LIMIT 1, 1

See MySql reference manual: SELECT Syntax

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15
aioobe
whilst ordering by the number you wish to get the second-highest of.
icio
Thanks. Updated
aioobe
A: 

Maybe:

SELECT * FROM table ORDER BY value DESC LIMIT 1, 1
MAZ
Maybe..? Btw, if you indent your code by four spaces you will get a prettier output.
Patrick
+10  A: 
select max(val) from table where val < (select max(val) form table) 
Pranay Rana
+1  A: 
SELECT E.lastname, E.salary FROM employees E
WHERE 2 = (SELECT COUNT(*) FROM employess E2
            WHERE E2.salary > E.salary)

Taken from here
This works in almost all Dbs

Binoj Antony
I believe the > must be >=. Plus, this won't work if any of the higher ranked values have multiple entries (say if there are 2 employees with the same highest salary, and you're trying to get the employees with the 2nd highest salary)
potatopeelings
@Binoj Antony: doesn't that get the third? If it has 2 larger values... but otherwise looks peachy.
ANeves
+2  A: 
Select Top 1 sq.ColumnToSelect
From
(Select Top 2 ColumnToSelect
From MyTable
Order by ColumnToSelect Desc
)sq
Order by sq.ColumnToSelect asc
Barry
A: 

one solution would be like this:

SELECT var FROM table ORDER BY var DESC LIMIT 1,1
oezi
+3  A: 

select top 2 field_name from table_name order by field_name desc limit 1

Avadhesh
When you use limit you can't use TOPTop is for SQL Server
Madhivanan
A: 

Cool, this is almost like Code Golf.

Microsoft SQL Server 2005 and higher:

SELECT *
FROM (
    SELECT 
        *,
        row_number() OVER (ORDER BY var DESC) AS ranking
    FROM table
) AS q
WHERE ranking = 2
littlegreen
You'd need to use `DENSE_RANK` to account for ties.
Martin Smith
+1  A: 

Try this

SELECT * FROM 
(SELECT empno, deptno, sal,
DENSE_RANK() OVER (PARTITION BY deptno ORDER BY sal DESC NULLS LAST) DENSE_RANK
FROM emp)
WHERE DENSE_RANK = 2;

This works in both Oracle & Sql Server

Bharat
Your code generates a syntax error on SQL Server. No doubt could be ported, though.
onedaywhen
A: 

Try this

SELECT TOP 1 Column FROM Table WHERE Column < (SELECT MAX(Column) FROM Table) 
ORDER BY Column DESC

SELECT TOP 1 Column FROM (SELECT TOP <n> Column FROM Table ORDER BY Column DESC) 

ORDER BY ASC

change the n to get the value of any position

Anuraj