In this section you will learn how to get record of employee having second highest salary.
In this section you will learn how to get record of employee having second highest salary.In this section you will learn how to get record of employee having second highest salary.
Find second highest salary :
For finding the highest salary you can directly use MAX(salary) function and for lowest salary you can use MIN(salary) function. There is no direct method to find out second highest salary so you can write different logical query to get second highest salary.
Employee Table : -
Example :
In this example we are finding the second highest salary of an employee.
Arrange record in descending order of salary and limit it to the second one.
Your query looks like -
sql = "SELECT * FROM employee ORDER BY salary DESC LIMIT 1,1"
SecondHighestSalary.java -
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; class SecondHighestSalary { public static void main(String[] args) { System.out.println("Finding second highest salary Example..."); Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "employees"; String driverName = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "root"; Statement statement = null; ResultSet rs; try { Class.forName(driverName); conn = DriverManager .getConnection(url + dbName, userName, password); statement = conn.createStatement(); String sql = "SELECT * FROM employee ORDER BY salary DESC LIMIT 1,1"; rs = statement.executeQuery(sql); System.out.println("EmpId\tName\tSalary"); System.out.println("----------------------"); while (rs.next()) { int roll = rs.getInt("emp_id"); String name = rs.getString("name"); long salary = rs.getLong("salary"); System.out.println(roll + "\t" + name + "\t" + salary); } conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
Output :
Finding second highest salary Example... EmpId Name Salary ---------------------- 2 Roxi 25000