Filtering data is one of the most powerful features of SQL. In real-world applications, databases store thousands or even millions of records, but users rarely need all of them at once. The WHERE clause allows us to filter records and retrieve only the data that matches specific conditions. This makes queries more efficient, meaningful, and useful for reporting and decision-making.
The WHERE clause is used to filter rows based on one or more conditions. Only the rows that satisfy the condition will be included in the result set.
SELECT * FROM employees
WHERE department = 'Sales';
This query retrieves only those employees whose department is Sales.
employees table.Sales, that row is returned.Comparison operators are used in the WHERE clause to compare values.
SELECT first_name, last_name, salary
FROM employees
WHERE salary > 50000;
This query returns employees whose salary is more than 50,000.
SELECT first_name, hire_date
FROM employees
WHERE hire_date < '2020-01-01';
This retrieves employees who joined the company before January 1, 2020.
SELECT first_name, salary
FROM employees
WHERE salary != 60000;
This returns employees whose salary is not equal to 60,000.
| Operator | Meaning |
|---|---|
| = | Equal |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal |
| <= | Less than or equal |
| != or <> | Not equal |
Logical operators allow multiple conditions to be combined in a WHERE clause.
SELECT * FROM employees
WHERE department = 'Sales' AND salary > 50000;
SELECT * FROM employees
WHERE department = 'Sales' OR department = 'Marketing';
SELECT * FROM employees
WHERE NOT department = 'IT';
The BETWEEN operator is used to filter values within a specific range.
SELECT first_name, last_name, salary
FROM employees
WHERE salary BETWEEN 40000 AND 60000;
The IN operator checks whether a value matches any value in a given list.
SELECT * FROM employees
WHERE department IN ('Sales', 'Marketing', 'HR');
The LIKE operator is used for pattern-based searches, especially with text data.
SELECT * FROM employees
WHERE first_name LIKE 'J%';
Returns employees whose first name starts with J.
SELECT * FROM employees
WHERE email LIKE '%gmail%';
Returns employees whose email contains the word gmail.
SELECT * FROM employees
WHERE first_name LIKE '_____';
Returns employees whose first name has exactly five characters.
| Wildcard | Description |
|---|---|
| % | Matches zero or more characters |
| _ | Matches exactly one character |
NULL represents missing or unknown data. It is not equal to zero or an empty string.
SELECT * FROM employees
WHERE email IS NULL;
Returns employees who do not have an email address.
SELECT * FROM employees
WHERE email IS NOT NULL;
Returns employees who have an email address.
= NULL will not workParentheses can be used to control execution order.
= NULL instead of IS NULL