WHERE Clause in SQL

WHERE Clause in SQL

The WHERE clause in SQL is used to filter records in a query based on specified conditions. It is typically applied in SELECT, UPDATE, DELETE, and other SQL statements to limit the rows affected or returned by the query.


Key Points

  1. Conditional Filtering:
    The WHERE clause filters rows based on one or more conditions, ensuring only relevant data is retrieved or affected.

  2. Supports Logical and Comparison Operators:
    You can use operators like =, >, <, LIKE, IN, BETWEEN, and logical operators like AND, OR, and NOT to form complex conditions.


Syntax

SELECT column1, column2, ...
FROM table_name
WHERE condition;

Example

Basic Filtering

SELECT first_name, last_name
FROM employees
WHERE department = 'HR';
  • Retrieves the first_name and last_name of employees who work in the 'HR' department.

Using Comparison Operators

SELECT first_name, salary
FROM employees
WHERE salary > 50000;
  • Returns employees with a salary greater than 50,000.

When to Use the WHERE Clause

  • To filter rows in a table based on specific conditions.

  • To refine data retrieval for reporting and analytics.

  • To apply conditions before performing actions like updating or deleting rows.

Note: If no rows match the condition, the query returns an empty result set.