The WHERE
clause in SQL is used to filter records and fetch only those that fulfill a specified condition. It is an essential part of SQL queries when you need to work with a subset of the data from a table based on some criteria. In this tutorial, we will explore the basics of the WHERE
clause and how to use it effectively in SQL queries.
The basic syntax of the WHERE
clause is as follows:
sql1SELECT column1, column2, ... 2FROM table_name 3WHERE condition;
column1, column2, ...
: The columns or fields you want to retrieve.table_name
: The name of the table from which to retrieve the data.condition
: The condition that must be met for a record to be included in the result set.You can use various operators with the WHERE
clause to form conditions:
=
: Equal to<>
or !=
: Not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal tosql1SELECT * FROM Employees 2WHERE Department = 'Sales';
This query retrieves all records from the Employees
table where the Department
is 'Sales'.
You can combine multiple conditions using the AND
and OR
logical operators:
sql1SELECT * FROM Employees 2WHERE Department = 'Sales' AND Salary > 50000;
This query returns all employees from the Sales
department with a salary greater than 50,000.
sql1SELECT * FROM Employees 2WHERE Department = 'Sales' OR Department = 'Marketing';
This query retrieves all employees from either the Sales
or Marketing
departments.
The IN
operator allows you to specify multiple values in a WHERE
clause.
sql1SELECT * FROM Employees 2WHERE Department IN ('Sales', 'Marketing', 'IT');
This query returns all employees who work in Sales
, Marketing
, or IT
departments.
The BETWEEN
operator selects values within a given range.
sql1SELECT * FROM Employees 2WHERE Salary BETWEEN 40000 AND 60000;
This query returns all employees whose salary is between 40,000 and 60,000.
The LIKE
operator is used to search for a specified pattern in a column.
sql1SELECT * FROM Employees 2WHERE FirstName LIKE 'J%';
This query retrieves all employees whose first name starts with the letter 'J'.
The NOT
operator is used to exclude records that match the condition.
sql1SELECT * FROM Employees 2WHERE NOT Department = 'Sales';
This query returns all employees who do not work in the Sales
department.
WHERE
clause is specific enough to filter out the unwanted records.()
to group conditions when combining AND
and OR
to control the order of evaluation.NULL
values; comparisons with NULL
using the =
operator will not match. Use IS NULL
or IS NOT NULL
instead.LIKE
, remember that %
represents zero or more characters, and _
represents a single character.WHERE
clause conditions.