JDBC : Find Highest salary


 

JDBC : Find Highest salary

In this tutorial, we are showing how to find record of highest salary employee.

In this tutorial, we are showing how to find record of highest salary employee.

JDBC : Find Highest salary

In this tutorial, we are showing how to find record of highest salary employee.

MAX() :

MAX() method returns the highest value of the specified field. So when you want to get highest value of any field just use MAX method in your query as -

sql = SELECT MAX(salary) FROM employee

Employee Table :  -

Example : In the following example we are displaying record of such employee who has highest salary among all. For that we are using MAX() function.

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

class JDBCHighestSalary {
	public static void main(String[] args) {
		System.out.println("Finding 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 WHERE salary=(SELECT MAX(salary) FROM employee)";

			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 Highest salary Example...
EmpId	Name	Salary
----------------------
3	Linda	30000

Ads