Find max and second max salary for a MySQL Employee table?


You can get max and second max salary from an Employee table using LIMIT OFFSET. The syntax is as follows −

SELECT yourColumnName1,yourColumnName2,....N from yourTableName ORDER BY
yourColumnName desc limit 2 offset 0;

To understand the above syntax, let us 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 following is the query to get the max and second max salary using limit offset −

mysql> select EmployeeId,Employeename,EmployeeSalary from EmployeeMaxAndSecondMaxSalary order by
   -> EmployeeSalary desc limit 2 offset 0;

The output displays the record of 2 employees with the maximum salary −

+------------+--------------+----------------+
| EmployeeId | Employeename | EmployeeSalary |
+------------+--------------+----------------+
|          6 | David        |          89990 |
|          8 | Robert       |          76543 |
+------------+--------------+----------------+
2 rows in set (0.00 sec)

Updated on: 30-Jun-2020

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements