Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select second largest from a table without limit

Tags:

sql

select

mysql

How we can select the second largest mark or whatever from a table without using the LIMIT ? I know it is possible using LIMIT, but is it possible without using that?

Suppose we have the columns id and marks.

like image 526
viMaL Avatar asked Oct 19 '10 10:10

viMaL


People also ask

How do you find the second largest number in a table?

SELECT MAX (column_name) FROM table_name WHERE column_name NOT IN (SELECT Max (column_name) FROM table_name); First we selected the max from that column in the table then we searched for the max value again in that column with excluding the max value which has already been found, so it results in the 2nd maximum value.

How do I find the second largest record in SQL?

Output- Now, to find the second highest salary, we nest the above query into another query as written below. SELECT MAX(SALARY) FROM Employee WHERE SALARY < (SELECT MAX(SALARY) FROM Employee);

How do I SELECT the third highest value 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.


2 Answers

Assuming marks is unique, following query gives you the second largest mark.

SELECT   MAX(marks)
FROM     ATable
WHERE    marks < (SELECT MAX(marks) FROM ATable)

To get the entire record, you could wrap this in an INNER JOIN

SELECT  t1.*
FROM    ATable t1
        INNER JOIN (
          SELECT   marks = MAX(marks)
          FROM     ATable
          WHERE    marks < (SELECT MAX(marks) FROM ATable)
        ) t2 ON t2. marks = t1.marks
like image 144
Lieven Keersmaekers Avatar answered Nov 26 '22 11:11

Lieven Keersmaekers


select max(number), id 
from <tableName>
where number < (select max(number) from <tableName>)
like image 41
Chinmayee G Avatar answered Nov 26 '22 11:11

Chinmayee G