In SQL, the WHERE
clause is used to filter rows returned by a SELECT
, UPDATE
, or DELETE
statement based on specified conditions. It allows you to specify criteria that must be met for a row to be included in the result set or affected by the operation.
Here's the basic syntax of the WHERE
clause in a SELECT
statement:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Explanation of each part:
SELECT
: Keyword indicating that you want to retrieve data from a table.column1, column2, ...
: The columns you want to retrieve from the table.FROM
: Keyword indicating the table from which you want to retrieve data.table_name
: The name of the table from which you want to retrieve data.WHERE
: Keyword indicating that you want to filter the rows based on specified conditions.condition
: The condition(s) that must be met for a row to be included in the result set. It can consist of comparisons, logical operators, and functions.Example:
Suppose we have a table called employees
with columns employee_id
, first_name
, last_name
, and department
. We want to retrieve the names of employees who work in the Sales department:
SELECT first_name, last_name
FROM employees
WHERE department = 'Sales';
In this example:
WHERE
clause filters the rows to include only those where the department
column equals 'Sales'
.first_name
and last_name
columns of employees who work in the Sales department.You can also use the WHERE
clause in UPDATE
and DELETE
statements to specify which rows should be updated or deleted based on certain conditions.