
When working with a database, you rarely need every record in a table. You might want to find customers from a particular city, products within a specific price range, employees earning more than a certain salary, or orders placed on a particular date.
This is where the SQL WHERE clause becomes useful.
The WHERE clause allows you to filter database records based on specific conditions. Instead of retrieving every row, you can return only the rows that match your requirements.
For example, imagine an online store with thousands of products. If you want to find products priced below ₹1,000, you can use:
SELECT *
FROM products
WHERE price < 1000;This query returns only products whose prices are below ₹1,000.
In this guide, you'll learn:
What the SQL
WHEREclause is.Its syntax and how it works.
How to use comparison and logical operators.
How to filter data with
IN,BETWEEN, andLIKE.How to handle
NULLvalues.How to combine multiple filtering conditions.
The difference between
WHEREandHAVING.Common mistakes and SQL filtering best practices.
Let's begin with the fundamentals.
What Is the SQL WHERE Clause?
The SQL WHERE clause is used to filter rows in a database table according to a specified condition.
Only rows that satisfy the condition are included in the query results. Rows for which the condition evaluates to false or unknown are excluded.
The WHERE clause is commonly used with SELECT, UPDATE, and DELETE statements.
For example, consider this employees table:
employee_id | name | department | salary |
|---|---|---|---|
1 | Rahul | IT | 60000 |
2 | Priya | HR | 45000 |
3 | Amit | IT | 75000 |
4 | Neha | Finance | 55000 |
5 | Karan | IT | 50000 |
Suppose you want to retrieve employees who work in the IT department.
You can write:
SELECT *
FROM employees
WHERE department = 'IT';The result contains only employees from the IT department.
employee_id | name | department | salary |
|---|---|---|---|
1 | Rahul | IT | 60000 |
3 | Amit | IT | 75000 |
5 | Karan | IT | 50000 |
The database evaluates the condition for each relevant row and returns the matching records.
In simple terms, the WHERE clause tells SQL which rows you want to retrieve or modify.
SQL WHERE Clause Syntax
The basic syntax of a SELECT statement using WHERE is:
SELECT column1, column2, ...
FROM table_name
WHERE condition;Here's what each part means:
SELECT: Specifies the columns you want to retrieve.FROM: Specifies the table containing the data.WHERE: Defines the filtering condition.condition: An expression that determines which rows match.
For example:
SELECT name, salary
FROM employees
WHERE salary > 50000;This query retrieves the names and salaries of employees earning more than 50,000.
You can select specific columns or use SELECT * to retrieve all columns.
For most application queries, selecting only the columns you need is preferable because it avoids transferring unnecessary data.
SQL WHERE Clause Operators
The WHERE clause supports several operators for filtering records.
The most commonly used categories are:
Operator Category | Operators | Purpose |
|---|---|---|
Comparison |
| Compare values |
Logical |
| Combine or negate conditions |
Range |
| Filter values within or outside a range |
List |
| Match values against a list |
Pattern matching |
| Match text patterns |
Null checking |
| Check for missing or unknown values |
Existence |
| Check whether a subquery returns rows |
Let's explore these operators with practical examples.
1. Using Comparison Operators in SQL
Comparison operators allow you to compare one value with another.
They are particularly useful for filtering numerical values, dates, and text.
Equal To (=)
The equal operator returns rows where a column matches a specified value.
SELECT *
FROM employees
WHERE department = 'IT';This query returns employees whose department is IT.
Not Equal To (<> or !=)
The not-equal operator filters out rows matching a particular value.
SELECT *
FROM employees
WHERE department <> 'HR';This returns employees whose department is not HR.
Both <> and != are supported by many popular database systems, but <> is the standard SQL not-equal operator and is a good choice for portable SQL.
Greater Than (>)
SELECT *
FROM employees
WHERE salary > 60000;This retrieves employees earning more than 60,000.
An employee earning exactly 60,000 will not be included.
Less Than (<)
SELECT *
FROM employees
WHERE salary < 60000;This returns employees earning less than 60,000.
Greater Than or Equal To (>=)
SELECT *
FROM employees
WHERE salary >= 60000;This includes employees earning exactly 60,000 as well as those earning more.
Less Than or Equal To (<=)
SELECT *
FROM employees
WHERE salary <= 50000;This returns employees earning 50,000 or less.
Comparison Operators Summary
Operator | Meaning | Example |
|---|---|---|
| Equal to |
|
| Not equal to |
|
| Not equal to in many databases |
|
| Greater than |
|
| Less than |
|
| Greater than or equal to |
|
| Less than or equal to |
|
These operators form the foundation of SQL filtering.
2. Using the AND Operator
The AND operator combines multiple conditions.
A row is returned only when all the specified conditions are true.
Suppose you want employees who work in IT and earn more than 50,000.
SELECT *
FROM employees
WHERE department = 'IT'
AND salary > 50000;The query checks two conditions:
The employee must work in IT.
The employee's salary must exceed 50,000.
Only employees satisfying both conditions are returned.
For example, Rahul and Amit from our sample data match these conditions, while Karan does not because his salary is exactly 50,000.
Using Multiple AND Conditions
You can combine more than two conditions:
SELECT *
FROM employees
WHERE department = 'IT'
AND salary > 50000
AND employee_id > 1;This returns employees who work in IT, earn more than 50,000, and have an employee ID greater than 1.
Use AND when every condition must be satisfied.
3. Using the OR Operator
The OR operator allows a row to match when at least one specified condition is true.
For example, suppose you want employees who work in either IT or HR.
SELECT *
FROM employees
WHERE department = 'IT'
OR department = 'HR';This returns employees from both departments.
You can also combine different types of conditions:
SELECT *
FROM employees
WHERE department = 'IT'
OR salary > 60000;This returns employees who work in IT or earn more than 60,000.
An employee does not need to satisfy both conditions.
AND vs. OR
Feature | AND | OR |
|---|---|---|
Requirement | Every condition must be true | At least one condition must be true |
Typical use | Narrowing results | Matching alternatives |
Example | IT employees earning above 50,000 | IT employees or anyone earning above 60,000 |
Understanding the difference between AND and OR is essential when building complex SQL queries.
4. Using the NOT Operator
The NOT operator reverses a condition.
For example, to retrieve employees who do not work in IT, you can write:
SELECT *
FROM employees
WHERE NOT department = 'IT';You can also use the not-equal operator:
SELECT *
FROM employees
WHERE department <> 'IT';Both queries exclude employees whose department is IT.
NOT can also be used with other operators:
SELECT *
FROM employees
WHERE salary NOT BETWEEN 40000 AND 60000;This returns employees whose salaries fall outside the inclusive range from 40,000 through 60,000.
Remember that NOT does not make a comparison involving NULL true. Null handling requires special care, which we'll cover later.
5. Using the BETWEEN Operator
The BETWEEN operator filters values within a specified range.
It includes both the lower and upper boundaries.
Example: Filter Employees by Salary
SELECT *
FROM employees
WHERE salary BETWEEN 50000 AND 70000;This query returns employees whose salaries are at least 50,000 and at most 70,000.
It is equivalent to:
SELECT *
FROM employees
WHERE salary >= 50000
AND salary <= 70000;Using BETWEEN with Dates
Suppose you have an orders table containing an order_date column.
You can retrieve orders within a date range:
SELECT *
FROM orders
WHERE order_date BETWEEN '2026-01-01' AND '2026-01-31';For a column containing dates without a time component, this retrieves dates from January 1 through January 31, 2026, inclusive.
Important: If order_date contains timestamps, the upper boundary may represent midnight at the start of January 31. That can exclude orders placed later that day.
For timestamp columns, a half-open range is usually safer:
SELECT *
FROM orders
WHERE order_date >= '2026-01-01'
AND order_date < '2026-02-01';This includes all timestamps in January, regardless of the time of day.
Date literal formats and timestamp behavior can vary by database system, so use the appropriate syntax for your database.
6. Using the IN Operator
The IN operator checks whether a value matches any value in a specified list.
It is useful when you want to filter records based on several possible values.
For example, to retrieve employees from IT, HR, or Finance:
SELECT *
FROM employees
WHERE department IN ('IT', 'HR', 'Finance');This is more concise than writing multiple OR conditions:
SELECT *
FROM employees
WHERE department = 'IT'
OR department = 'HR'
OR department = 'Finance';Both queries express the same basic filtering requirement.
Using NOT IN
The NOT IN operator excludes values in a list.
SELECT *
FROM employees
WHERE department NOT IN ('HR', 'Finance');This returns employees whose department is neither HR nor Finance, provided the department value is not NULL.
Important: If a NOT IN list contains NULL, its behavior can surprise you because comparisons involving unknown values do not evaluate to true. If the list comes from a subquery, consider whether NOT EXISTS would be safer.
7. Using the LIKE Operator
The LIKE operator matches text against a pattern.
It is useful when you know only part of a value, such as a customer's name, an email address, or a product description.
SQL commonly uses two wildcard characters with LIKE:
%matches zero or more characters._matches exactly one character.
Example 1: Find Names Starting with a Letter
SELECT *
FROM employees
WHERE name LIKE 'A%';This retrieves employees whose names start with A.
Examples include Amit and any other matching name.
Example 2: Find Names Ending with a Letter
SELECT *
FROM employees
WHERE name LIKE '%a';This finds names ending with a, subject to the database's text-comparison and collation rules.
Example 3: Find Names Containing Text
SELECT *
FROM employees
WHERE name LIKE '%it%';This matches names containing the sequence it anywhere in the text.
Example 4: Match a Single Character
SELECT *
FROM employees
WHERE name LIKE '_a%';This matches names whose second character is a.
For example, Karan matches because its second character is a.
LIKE Operator Examples
Pattern | Meaning |
|---|---|
| Starts with A |
| Ends with a |
| Contains it |
| Second character is a |
| Starts with Ra, followed by two characters, and ends with l |
Note: Whether LIKE is case-sensitive depends on the database and its collation or comparison rules. For example, PostgreSQL also provides ILIKE for case-insensitive pattern matching.
8. Using IS NULL and IS NOT NULL
In SQL, NULL represents a missing or unknown value. It is not the same as zero, an empty string, or the text 'NULL'.
You cannot reliably test for null values using ordinary equality comparisons.
For example, this is incorrect:
SELECT *
FROM employees
WHERE department = NULL;Instead, use IS NULL:
SELECT *
FROM employees
WHERE department IS NULL;This returns employees whose department value is missing or unknown.
Find Records Without NULL Values
To retrieve employees whose department is available, use:
SELECT *
FROM employees
WHERE department IS NOT NULL;Why Doesn't = NULL Work?
SQL uses three-valued logic in which a condition can evaluate to:
TRUEFALSEUNKNOWN
Comparisons involving NULL generally produce UNKNOWN, not TRUE or FALSE.
Since a WHERE clause keeps only rows for which the condition evaluates to true, an expression such as department = NULL does not identify null values.
Use IS NULL and IS NOT NULL instead.
9. Combining Multiple WHERE Conditions
Real-world queries often require several conditions.
For example, imagine an e-commerce website that wants to find products from the Electronics category priced between 10,000 and 50,000.
SELECT product_name, category, price
FROM products
WHERE category = 'Electronics'
AND price BETWEEN 10000 AND 50000;This query returns products that satisfy both conditions.
You can also combine AND, OR, and parentheses to express more complex requirements.
Example: Use Parentheses to Control Conditions
Suppose you want employees who work in IT or HR and earn more than 50,000.
SELECT *
FROM employees
WHERE (department = 'IT' OR department = 'HR')
AND salary > 50000;The parentheses group the department conditions together.
Without parentheses:
SELECT *
FROM employees
WHERE department = 'IT'
OR department = 'HR'
AND salary > 50000;SQL evaluates AND before OR, so the second query is interpreted as:
SELECT *
FROM employees
WHERE department = 'IT'
OR (department = 'HR' AND salary > 50000);This means all IT employees are included regardless of salary, while HR employees must earn more than 50,000.
The two queries therefore return different results.
Best practice: Use parentheses whenever mixing AND and OR if the intended grouping is not immediately obvious.
10. Using WHERE with UPDATE
The WHERE clause is not limited to retrieving data. It can also determine which rows an UPDATE statement modifies.
Suppose you want to increase the salary of employees in the IT department.
UPDATE employees
SET salary = salary + 5000
WHERE department = 'IT';This increases the salary of IT employees by 5,000.
Without a WHERE clause, the statement would update every row in the table.
Update a Specific Employee
UPDATE employees
SET salary = 70000
WHERE employee_id = 1;This changes the salary of the employee whose ID is 1.
Before running an update on important data, verify the condition with a corresponding SELECT query:
SELECT *
FROM employees
WHERE employee_id = 1;For critical changes, use an appropriate transaction and confirm the affected rows before committing.
11. Using WHERE with DELETE
The WHERE clause can also specify which rows should be deleted.
For example, suppose you want to remove cancelled orders from an orders table.
DELETE FROM orders
WHERE status = 'Cancelled';This deletes rows whose status is Cancelled.
Without a WHERE clause:
DELETE FROM orders;The statement deletes all rows from the table, although the table itself remains.
Best Practices Before DELETE
Before deleting data:
Check the target records with
SELECT.Confirm that the filtering condition is correct.
Use a transaction where supported and appropriate.
Verify the number of affected rows.
Ensure you have a recovery strategy for important data.
For example:
SELECT *
FROM orders
WHERE status = 'Cancelled';Review the results before executing the corresponding DELETE.
12. Using WHERE with a Subquery
A subquery is a query nested inside another SQL statement.
You can use a subquery within a WHERE clause to filter rows based on data from another query.
Example: Find Employees Earning More Than the Average Salary
SELECT name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);The inner query calculates the average salary across the employee table.
The outer query returns employees whose salaries exceed that average.
This approach is useful when the filtering value must be calculated from the data rather than supplied manually.
Using EXISTS
The EXISTS operator checks whether a subquery returns at least one row.
Suppose you have customers and orders tables. You want to find customers who have placed at least one order.
SELECT c.customer_id, c.name
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.customer_id
);The subquery checks whether each customer has a matching order.
Only customers with at least one matching order are returned.
EXISTS is particularly useful when filtering rows based on whether related records exist.
13. Difference Between WHERE and HAVING
The WHERE and HAVING clauses both filter data, but they operate at different stages of a query.
WHEREfilters individual rows before grouping and aggregation.HAVINGfilters groups afterGROUP BYand aggregate calculations.
Consider a sales table containing sales records for different products.
Suppose you want to calculate the total sales for each product but display only products whose total sales exceed 50,000.
SELECT product_name, SUM(amount) AS total_sales
FROM sales
GROUP BY product_name
HAVING SUM(amount) > 50000;The query groups sales by product and then filters the resulting groups.
Using WHERE and HAVING Together
You can use both clauses in the same query.
For example, to calculate product sales for 2026 and display only products with total sales above 50,000:
SELECT product_name, SUM(amount) AS total_sales
FROM sales
WHERE sale_date >= '2026-01-01'
AND sale_date < '2027-01-01'
GROUP BY product_name
HAVING SUM(amount) > 50000;Here:
WHEREselects sales records from 2026.GROUP BYgroups the selected records by product.SUM(amount)calculates each product's total.HAVINGretains only groups whose total exceeds 50,000.
WHERE vs. HAVING Comparison
Feature | WHERE | HAVING |
|---|---|---|
Filters | Individual rows | Groups of rows |
Applied conceptually | Before grouping | After grouping |
Commonly used with aggregates | Filters input rows before aggregation | Filters aggregate results |
Example |
|
|
For a deeper understanding of grouping and aggregate functions, learning GROUP BY alongside WHERE and HAVING is highly recommended.
14. SQL WHERE Clause Performance Tips
Filtering conditions can influence how efficiently a database retrieves data.
Although the database optimizer determines the execution plan, following these practices can help you write more efficient queries.
1. Create Appropriate Indexes
Indexes can help databases locate matching rows without scanning every row in a table.
For example, if queries frequently filter employees by department, an index on the department column might help:
CREATE INDEX idx_employees_department
ON employees(department);However, an index is not automatically beneficial for every column or query. Its usefulness depends on factors such as table size, data distribution, query patterns, and write overhead.
Review the execution plan before adding indexes solely for performance reasons.
2. Avoid Functions on Filtered Columns When Possible
Consider this query:
SELECT *
FROM orders
WHERE EXTRACT(YEAR FROM order_date) = 2026;Applying a function to the date column can prevent some conventional indexes from being used efficiently, depending on the database and available indexes.
A range-based condition is often preferable:
SELECT *
FROM orders
WHERE order_date >= '2026-01-01'
AND order_date < '2027-01-01';This form can work well with an index on order_date.
The exact behavior depends on the database and execution plan.
3. Select Only the Columns You Need
Instead of retrieving every column:
SELECT *
FROM employees
WHERE department = 'IT';Consider:
SELECT name, salary
FROM employees
WHERE department = 'IT';Selecting only the necessary columns can reduce data transfer and may allow more efficient execution plans.
4. Use the Correct Data Types
Store values using suitable database types.
For example, use numeric columns for prices and date or timestamp columns for dates rather than storing everything as text.
Correct data types make comparisons clearer and can avoid unnecessary conversions.
5. Avoid Unnecessary Wildcard Searches
A pattern such as:
SELECT *
FROM employees
WHERE name LIKE '%mit%';starts with a wildcard, which can make a conventional B-tree index less useful for the search.
If the application only needs names beginning with a particular prefix, a prefix search may be more index-friendly:
SELECT *
FROM employees
WHERE name LIKE 'Ami%';The actual performance depends on the database, collation, index type, and query plan.
6. Use EXPLAIN to Inspect Query Plans
Many databases provide tools for examining query execution plans.
For example, PostgreSQL supports:
EXPLAIN
SELECT name, salary
FROM employees
WHERE department = 'IT';This helps you understand how the database plans to execute the query.
In PostgreSQL, EXPLAIN ANALYZE executes the statement and reports actual execution statistics. Use it thoughtfully, particularly for statements that modify data.
Important: Never assume that adding an index or rewriting a condition will improve performance in every situation. Test with representative data and inspect the execution plan.
15. Common SQL WHERE Clause Mistakes
Understanding common mistakes will help you write correct and maintainable SQL.
Mistake 1: Forgetting Quotes Around Text Values
Incorrect:
SELECT *
FROM employees
WHERE department = IT;Correct:
SELECT *
FROM employees
WHERE department = 'IT';In ordinary SQL string literals, text values should be enclosed in single quotes.
Identifiers such as table and column names follow different rules.
Mistake 2: Using = NULL
Incorrect:
SELECT *
FROM employees
WHERE department = NULL;Correct:
SELECT *
FROM employees
WHERE department IS NULL;Use IS NULL to identify missing or unknown values.
Mistake 3: Forgetting the WHERE Clause in UPDATE
Potentially dangerous:
UPDATE employees
SET salary = 70000;This changes the salary of every employee.
To update a specific employee, include an appropriate condition:
UPDATE employees
SET salary = 70000
WHERE employee_id = 1;Always verify your filtering condition before modifying important data.
Mistake 4: Forgetting the WHERE Clause in DELETE
Potentially dangerous:
DELETE FROM employees;This deletes all rows from the table.
To remove only a specific employee:
DELETE FROM employees
WHERE employee_id = 1;Mistake 5: Using AND Instead of OR
Suppose you want employees from IT or HR.
Incorrect:
SELECT *
FROM employees
WHERE department = 'IT'
AND department = 'HR';A single department value cannot simultaneously equal both IT and HR, so this condition won't match ordinary rows.
Correct:
SELECT *
FROM employees
WHERE department = 'IT'
OR department = 'HR';Alternatively, use:
SELECT *
FROM employees
WHERE department IN ('IT', 'HR');Mistake 6: Ignoring Operator Precedence
When combining AND and OR, missing parentheses can change the meaning of your query.
Use parentheses to make the intended logic explicit.
Mistake 7: Assuming NOT IN Handles NULL Like Ordinary Values
Consider a NOT IN expression whose list contains NULL. Comparisons may evaluate to unknown, resulting in fewer rows than expected.
If the list is produced by a subquery, investigate whether a correlated NOT EXISTS condition better expresses your intent.
Mistake 8: Using Incorrect Date Boundaries
When filtering timestamps, remember that a date-only upper boundary may represent midnight at the start of that day.
Use an inclusive lower boundary and exclusive upper boundary when filtering full calendar periods.
Frequently Asked Questions (FAQs)
1. What is the WHERE clause in SQL?
The WHERE clause filters rows based on specified conditions. It is commonly used with SELECT, UPDATE, and DELETE statements to determine which records should be retrieved or modified.
2. What is the basic syntax of the SQL WHERE clause?
The basic syntax is:
SELECT column_name
FROM table_name
WHERE condition;Replace the table name, column name, and condition with the values appropriate for your query.
3. Can we use multiple conditions in a WHERE clause?
Yes. You can combine multiple conditions using AND, OR, and NOT. Parentheses help control how complex conditions are grouped.
4. What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping, while HAVING filters groups after aggregation. Use WHERE for conditions on input rows and HAVING for conditions involving aggregate results.
5. Can we use WHERE with UPDATE and DELETE?
Yes. The WHERE clause identifies the rows an UPDATE or DELETE statement should affect. Without it, these statements generally apply to every row in the target table.
6. What is the difference between IN and BETWEEN?
IN checks whether a value matches one of several specified values. BETWEEN checks whether a value falls within an inclusive range.
Example:
WHERE department IN ('IT', 'HR')WHERE salary BETWEEN 40000 AND 600007. How do I check for NULL values in SQL?
Use IS NULL to find rows containing null values and IS NOT NULL to find rows with non-null values.
SELECT *
FROM employees
WHERE department IS NULL;8. Is WHERE mandatory in SQL?
No. It is optional in statements where it is supported. However, omitting it from an UPDATE or DELETE statement can affect every row in the target table.
9. Can we use a subquery inside WHERE?
Yes. You can use subqueries with operators such as IN, comparison operators, and EXISTS.
For example:
SELECT name
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);10. Does WHERE improve SQL query performance?
A WHERE clause limits the rows returned or processed by the relevant query operations, but it does not guarantee faster execution in every case. Performance depends on the database, indexes, data distribution, and execution plan.
11. What happens when a WHERE condition evaluates to NULL or UNKNOWN?
SQL generally returns only rows for which the WHERE condition evaluates to TRUE. Rows for which it evaluates to FALSE or UNKNOWN are excluded.
12. Can I use LIKE and IN together?
Yes. You can combine different filtering expressions using AND or OR.
For example:
SELECT *
FROM employees
WHERE department IN ('IT', 'HR')
AND name LIKE 'A%';This returns employees from IT or HR whose names begin with A, subject to the database's pattern-matching rules.
Conclusion
The SQL WHERE clause is one of the most important tools for working with relational databases. It allows you to filter records, retrieve relevant information, and control which rows are modified or deleted.
In this guide, you learned how to use:
Comparison operators such as
=,>, and<=.Logical operators such as
AND,OR, andNOT.Range filtering with
BETWEEN.List filtering with
INandNOT IN.Pattern matching with
LIKE.Null checking with
IS NULLandIS NOT NULL.Subqueries and
EXISTS.Filtering with
UPDATEandDELETE.The difference between
WHEREandHAVING.Practical performance tips and common mistakes.
The best way to master SQL filtering is to practice with real datasets. Start with simple conditions, combine multiple operators, and gradually work toward subqueries and more complex queries.
Remember: A well-written WHERE clause helps you retrieve the right records and avoid accidentally modifying data you didn't intend to change.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.
