In Advance Java, the WHERE clause is used with SQL queries inside JDBC to filter records retrieved from a database. It allows Java applications to fetch only the required data instead of entire tables.
SELECT, UPDATE, and DELETE statementsThe WHERE clause is written after the table name in an SQL query.
// SQL syntax using WHERE clause
SELECT column1, column2 FROM table_name WHERE condition;
// Fetch employee details with salary greater than 30000
String query = "SELECT * FROM employees WHERE salary > 30000";
Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
Only employee records whose salary is greater than 30000 will be retrieved. Rows that do not satisfy the WHERE condition are ignored by the database.
Click a button to see how the Java Query filters the database results:
| ID | Name | Dept | Salary |
|---|---|---|---|
| 101 | John Doe | HR | 45000 |
| 102 | Jane Smith | IT | 60000 |
| 103 | Robert Brown | Finance | 75000 |
| 104 | Emily Davis | IT | 55000 |
| 105 | Michael Wilson | HR | 48000 |
PreparedStatement to prevent SQL InjectionAND and OR conditionsLIKE operatorPreparedStatement