Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving the second most highest value from a table

Tags:

sql

tsql

How do I retrieve the second highest value from a table?

like image 941
siva Avatar asked Jun 15 '10 08:06

siva


People also ask

How do you select the top 2 maximum value in SQL?

Select TOP 2 * from Products where Price = (Select Max(Price) from Products);

How do you find the 2nd highest in Excel?

=LARGE(A1:A5, 2) This will give you the second largest value, without any fuss. The format of the LARGE Function is =LARGE(array, k), and it picks up the Kth largest value from the array.

How do you select the top 3 maximum value in SQL?

To get the maximum value from three different columns, use the GREATEST() function. Insert some records in the table using insert command. Display all records from the table using select statement.

How can find 2 and 3 highest salary in SQL?

Here is a way to do this task using dense_rank() function. Query : select * from( select ename, sal, dense_rank() over(order by sal desc)r from Employee) where r=&n; To find to the 2nd highest sal set n = 2 To find 3rd highest sal set n = 3 and so on.


3 Answers

select max(val) from table where val < (select max(val) form table) 
like image 69
Pranay Rana Avatar answered Oct 23 '22 12:10

Pranay Rana


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

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

See the 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
like image 29
aioobe Avatar answered Oct 23 '22 13:10

aioobe


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

like image 5
Avadhesh Avatar answered Oct 23 '22 12:10

Avadhesh