Find the Second largest value from MySql, MsSql, Sql Server table

Saturday, January 28, 2012


Finding Second Bigger or largest value from the table column in MySQL / MS SQL / SQLServer, here is the simple sql query to identify the Second toppest value from database table.

Using MAX(fieldname) function

salary_master: (Sample Data)

id     name        salary
1      AAA         20000
2      BBB         18000
3      CCC         19000

SELECT MAX(salary) from salary_master 
above Query will return output (Eg: 20000) the first largest or biggest value from table column.
Using SubQuery we will extract the less than maximum value data and than find the MAX
below the code which get the Maximum salary from salary_master table which was less than the maximum salary (ie., return records except 20000)
SELECT * from salary_master 
where salary < (SELECT MAX(salary) from salary_master)

Output:
id     name        salary
2      BBB         18000
3      CCC         19000



Now will process the MAX(salary) instead of * we will get the output Second Largest Value

SELECT MAX(salary) from salary_master 
where salary < (SELECT MAX(salary) from salary_master)

Output:
20000



No comments:

Post a Comment