
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Max and Second Max Salary for MySQL Employee Table Using Subquery
You can get max and second max salary from an Employee table using subquery.
Let us first create a table. The query to create a table is as follows −
mysql> create table EmployeeMaxAndSecondMaxSalary -> ( -> EmployeeId int, -> Employeename varchar(20), -> EmployeeSalary int -> ); Query OK, 0 rows affected (0.88 sec)
Insert some records in the table using insert command −
mysql> insert into EmployeeMaxAndSecondMaxSalary values(1,'John',34566); Query OK, 1 row affected (0.20 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(2,'Bob',56789); Query OK, 1 row affected (0.17 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(3,'Carol',44560); Query OK, 1 row affected (0.26 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(4,'Sam',76456); Query OK, 1 row affected (0.29 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(5,'Mike',65566); Query OK, 1 row affected (0.14 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(6,'David',89990); Query OK, 1 row affected (0.19 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(7,'James',68789); Query OK, 1 row affected (0.12 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(8,'Robert',76543); Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from EmployeeMaxAndSecondMaxSalary;
The following is the output.
+------------+--------------+----------------+ | EmployeeId | Employeename | EmployeeSalary | +------------+--------------+----------------+ | 1 | John | 34566 | | 2 | Bob | 56789 | | 3 | Carol | 44560 | | 4 | Sam | 76456 | | 5 | Mike | 65566 | | 6 | David | 89990 | | 7 | James | 68789 | | 8 | Robert | 76543 | +------------+--------------+----------------+ 8 rows in set (0.00 sec)
The query to get the max and second max salary using subquery −
mysql> select (select max(EmployeeSalary) from EmployeeMaxAndSecondMaxSalary) MaximumSalary, -> (select max(EmployeeSalary) from EmployeeMaxAndSecondMaxSalary -> where EmployeeSalary not in(select max(EmployeeSalary) from EmployeeMaxAndSecondMaxSalary)) as SecondMaximumSalary;
The following is the output displaying the top two salaries −
+---------------+---------------------+ | MaximumSalary | SecondMaximumSalary | +---------------+---------------------+ | 89990 | 76543 | +---------------+---------------------+ 1 row in set (0.00 sec)
Advertisements