0

How can I print the first two maximum values under an attribute (column) in a database table using SQL?

I have a column named salary that contains different rows, (approximately 10 rows). We need to print out the first two maximum values.

I know we can get the first maximum value by using max function, but what can I do if I need the first two values?

2
  • SQL Server or MySQL, which is it? Make up your mind
    – podiluska
    Aug 28, 2012 at 8:19
  • If you have like 1000, 1000, 900 in your table, then you need the 1000, 1000 as output or 1000 and 900. Aug 28, 2012 at 8:24

4 Answers 4

3

Perhaps something like this? (mysql)

select `salary` from `mytable` order by `salary` desc limit 2

As per Alex's answer, you can add the distinct keyword to ensure that you get two different values.

select distinct `salary` from `mytable` order by `salary` desc limit 2
3

In SQL Server

SELECT TOP 2 salary
from table
order by salary desc

In MySQL

SELECT salary
from table
order by salary desc
limit 2
0
select distinct salary from mytable order by salary desc limit 2;
0

Ok If you need only the two top, even if the are equal, the others have rigth, but if you need the top 2 number (and you don't care if there are multiple instance from them) you can use this:

SELECT 
Salary 
FROM Salaries
GROUP BY Salary
ORDER BY Salary DESC
LIMIT 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.