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
Conditional Filtering:
TheWHERE
clause filters rows based on one or more conditions, ensuring only relevant data is retrieved or affected.Supports Logical and Comparison Operators:
You can use operators like=
,>
,<
,LIKE
,IN
,BETWEEN
, and logical operators likeAND
,OR
, andNOT
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
andlast_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.