Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL. Is there any efficient way to find second lowest value?

Tags:

sql

subquery

db2

I have the following table:

 ItemID Price
    1   10
    2   20
    3   12
    4   10
    5   11

I need to find the second lowest price. So far, I have a query that works, but i am not sure it is the most efficient query:

select min(price)
from table
where itemid not in
(select itemid
from table
where price=
(select min(price)
from table));

What if I have to find third OR fourth minimum price? I am not even mentioning other attributes and conditions... Is there any more efficient way to do this?

PS: note that minimum is not a unique value. For example, items 1 and 4 are both minimums. Simple ordering won't do.

like image 242
Buras Avatar asked Jun 08 '13 00:06

Buras


People also ask

How do you find the second smallest value in SQL?

select min(price) from table where itemid not in (select itemid from table where price= (select min(price) from table));

How do I select the next minimum value in SQL?

To find the minimum value of a column, use the MIN() aggregate function; it takes as its argument the name of the column for which you want to find the minimum value. If you have not specified any other columns in the SELECT clause, the minimum will be calculated for all records in the table.

How do I find the second top record in SQL?

Method-1: Syntax: SELECT MAX (column_name) FROM table_name WHERE column_name NOT IN (SELECT Max (column_name) FROM table_name);


1 Answers

SELECT MIN( price )
FROM table
WHERE price > ( SELECT MIN( price )
                FROM table )
like image 61
Hashid Hameed Avatar answered Sep 21 '22 19:09

Hashid Hameed