SQL Filtering: WHERE, IN, OR, AND, and More
Learn how to filter and refine data efficiently using SQL's filtering operators.
What is Filtering in SQL?
Filtering in SQL allows you to retrieve only the rows that meet certain conditions. The most common filtering clause is WHERE
, which is used to limit the results based on specific criteria.
Using the WHERE Clause
The WHERE
clause is used to filter records based on a specified condition.
-- Basic WHERE clause
SELECT * FROM employees
WHERE department = 'Sales';
Combining Conditions with AND and OR
The AND
operator ensures that all conditions must be true, while OR
allows any one of the conditions to be true.
-- Using AND and OR
SELECT * FROM employees
WHERE department = 'Sales' AND salary > 50000;
Filtering with IN
The IN
operator is used to match multiple values without using multiple OR conditions.
-- Using IN for multiple values
SELECT * FROM employees
WHERE department IN ('Sales', 'Marketing', 'HR');
Using LIKE for Pattern Matching
The LIKE
operator is useful for filtering text based on patterns.
-- Using LIKE for pattern matching
SELECT * FROM employees
WHERE name LIKE 'J%';
Using BETWEEN for Ranges
The BETWEEN
operator allows filtering values within a range, inclusive of the boundary values.
-- Using BETWEEN for range filtering
SELECT * FROM employees
WHERE salary BETWEEN 40000 AND 60000;