← Back to Chapters

WHERE Clause in Advance Java

? WHERE Clause in Advance Java

? Quick Overview

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.

? Key Concepts

  • Used with SELECT, UPDATE, and DELETE statements
  • Applies conditions to database queries
  • Works with comparison, logical, and pattern-matching operators
  • Helps improve performance and security

? Syntax / Theory

The WHERE clause is written after the table name in an SQL query.

? View Code Example
// SQL syntax using WHERE clause
SELECT column1, column2 FROM table_name WHERE condition;

? Code Example (JDBC)

? View Code Example
// 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"));
}

? Live Output / Explanation

Explanation

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.

? Interactive Simulator

Click a button to see how the Java Query filters the database results:

String sql = "SELECT * FROM employees";
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

? Tips & Best Practices

  • Always use WHERE clause to avoid unnecessary data retrieval
  • Use PreparedStatement to prevent SQL Injection
  • Index columns used frequently in WHERE conditions
  • Avoid using WHERE without conditions in UPDATE or DELETE

? Try It Yourself

  • Retrieve students whose marks are greater than 60
  • Use WHERE with AND and OR conditions
  • Fetch records using LIKE operator
  • Modify the query using PreparedStatement