JDBC : Find Lowest salary


 

JDBC : Find Lowest salary

In this tutorial, we are showing how to find record of lowest salary in table employee.

In this tutorial, we are showing how to find record of lowest salary in table employee.

JDBC : Find Lowest salary

In this tutorial, we are showing how to find record of lowest salary in table employee.

MIN() :

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

sql = SELECT MIN(salary) FROM employee

Employee Table :  -

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

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

class JDBCMinSalary {
	public static void main(String[] args) {
		System.out.println("Finding Lowest 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 MIN(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 Lowest salary Example...
EmpId	Name	Salary
----------------------
4	Julu	15000

Ads