Home Tutorial Java Core JDBC : Find Third highest salary

 
 

JDBC : Find Third highest salary
Posted on: October 11, 2012 at 12:00 AM
Advertisement
In this section you will learn how to get record of employee having second highest salary.

JDBC : Find Third highest salary

In this section you will learn how to get record of employee having second highest salary.

Find Third 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 third highest salary so you can write different logical query to get third highest salary.

Employee Table :  -

Example :

In this example we are finding the third highest salary of an employee. Arrange record in descending order of salary and limit it to the third one.
Your sql query -
sql = "SELECT * FROM employee ORDER BY salary DESC LIMIT 2,1"

ThirdHighestSalary.java -

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

class ThirdHighestSalary {
	public static void main(String[] args) {
		System.out.println("Finding Third 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 2,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 Third highest salary Example...
EmpId	Name	Salary
----------------------
1	Jackson	20000
Advertisement

Related Tags for JDBC : Find Third highest salary :


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 11, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com