SQL WHERE Command: How to Filter Rows
In this article
The SQL WHERE command filters rows so that a query returns only the records that match a condition. You write it after the FROM clause (and after any JOIN) and before GROUP BY, ORDER BY, or LIMIT. For example, SELECT * FROM users WHERE country = 'US'; returns only users in the US. This guide walks through the syntax, the operators you will actually use, and the mistakes that cause wrong or empty results.
What You'll Need
- A SQL database you can query (MySQL, PostgreSQL, SQL Server, SQLite, or a cloud data warehouse all support WHERE with the same core syntax).
- A client to run queries: the database's command-line tool, a GUI such as pgAdmin or MySQL Workbench, or your application's query console.
- Permission to run SELECT statements on the table you want to filter.
- Basic familiarity with SELECT and FROM. If you can write
SELECT * FROM table_name;, you are ready.
Step-by-Step
- Start with a working SELECT. Run
SELECT * FROM orders;first and look at the data. Confirm the column names and the type of each column (text, number, date) because the type determines how you write the condition. - Add WHERE and one condition. Put WHERE immediately after the table name:
SELECT * FROM orders WHERE status = 'shipped';Text values go in single quotes; numbers do not:WHERE total > 100. - Use the right comparison operator. The standard set is
=,<>or!=(not equal),>,<,>=, and<=. For dates, compare with a quoted date literal such asWHERE order_date >= '2024-01-01'; ISO format YYYY-MM-DD works across the major databases. - Match patterns with LIKE.
WHERE email LIKE '%@example.com'finds addresses ending in that domain. The percent sign matches any number of characters and the underscore matches exactly one. LIKE is case-sensitive in some databases (PostgreSQL) and case-insensitive by default in others (MySQL with common collations), so check your database's behaviour if case matters. - Filter against a list with IN.
WHERE status IN ('shipped', 'delivered')is cleaner than chaining OR conditions. UseNOT INfor exclusion, but remember that NULL values in the list can make NOT IN return no rows at all. - Handle ranges with BETWEEN.
WHERE total BETWEEN 50 AND 200includes both endpoints. For dates, BETWEEN with a date-only upper bound excludes times later that day; use>= start AND < next_daywhen a timestamp column is involved. - Combine conditions with AND and OR. AND requires both conditions to be true; OR requires either. Mixing them without parentheses gives AND higher precedence, so write
WHERE (status = 'shipped' OR status = 'delivered') AND total > 100to make the grouping explicit. - Test for NULL correctly. NULL means unknown, so
WHERE discount = NULLnever matches. UseWHERE discount IS NULLorIS NOT NULLinstead. - Run the query and check the row count. Compare the number of rows returned with what you expect from the unfiltered table. If the count is zero unexpectedly, remove conditions one at a time until rows appear; the last removed condition is the culprit.
- Add ORDER BY and LIMIT after WHERE. They come later in the statement:
SELECT * FROM orders WHERE status = 'shipped' ORDER BY order_date DESC LIMIT 20;This returns the 20 most recent shipped orders.
Common Mistakes
- Quoting numbers or not quoting text.
WHERE total = '100'may work through implicit conversion in some databases but fails or behaves oddly in others. Match the literal to the column type. - Forgetting parentheses around OR.
WHERE status = 'shipped' OR status = 'delivered' AND total > 100does not mean what it looks like; AND binds first. - Using = NULL. It silently returns no rows. Always use IS NULL or IS NOT NULL.
- Assuming LIKE is case-insensitive. Behaviour varies by database and collation. Use LOWER(column) LIKE LOWER('%pattern%') or the database's case-insensitive operator when you need consistency.
- Putting WHERE in the wrong place. WHERE must come after FROM and JOIN but before GROUP BY, HAVING, ORDER BY, and LIMIT. HAVING filters grouped results; WHERE filters rows before grouping.
- Comparing dates as strings with the wrong format. '01/02/2024' is ambiguous and may sort incorrectly. Use ISO dates or the database's date functions.
Tips
- Select the specific columns you need instead of
SELECT *; it makes results easier to read and can be faster. - Use table aliases in joins so conditions stay readable:
WHERE o.status = 'shipped' AND c.country = 'US'. - When debugging, run the query without WHERE first, then add conditions back one at a time. This isolates the failing condition quickly.
- Keep a comment above complex WHERE clauses explaining the business rule, for example why a date range is split into two comparisons.
- For repeated filters, consider a view or a saved query so the logic lives in one place.
Troubleshooting
Query returns no rows. Check for NULL comparisons, mismatched quotes, and trailing spaces in text values. Run SELECT DISTINCT column FROM table; to see the exact stored values; 'Shipped' and 'shipped' are different in case-sensitive databases.
Query returns too many rows. An OR condition is probably too broad or missing parentheses. Add parentheses and test each branch separately.
Syntax error near WHERE. Confirm the clause order: FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. A missing quote or an unclosed parenthesis earlier in the statement often reports the error at WHERE.
Dates behave unexpectedly. If the column is a timestamp, a condition like order_date = '2024-05-01' matches only midnight exactly. Use a range: order_date >= '2024-05-01' AND order_date < '2024-05-02'.
Slow query. Filtering on an unindexed column can scan the whole table. Ask your database administrator whether an index on the filtered column is appropriate; do not add indexes to production without checking the impact on writes.
Frequently Asked Questions
Is WHERE the same in every SQL database?
The core syntax and operators are standard across MySQL, PostgreSQL, SQL Server, SQLite, and most warehouses. Differences appear in case sensitivity, date functions, and some pattern-matching extensions, so check your database's documentation for edge cases.
Can I use WHERE without FROM?
Yes, in many databases you can run SELECT 1 WHERE 1 = 1; to test an expression, but filtering real data always involves a FROM clause.
What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping; HAVING filters groups after GROUP BY. Use WHERE for column conditions and HAVING for aggregate conditions such as HAVING COUNT(*) > 5.
Can WHERE use a subquery?
Yes. For example, WHERE customer_id IN (SELECT id FROM customers WHERE country = 'US') filters rows against the result of another query. Keep subqueries small or use a JOIN when performance matters.
Why does NOT IN return nothing?
If the list or subquery contains a NULL, NOT IN evaluates to unknown for every row and returns no results. Filter out NULLs or use NOT EXISTS instead.
Does WHERE work with UPDATE and DELETE?
Yes, and it is essential there: UPDATE orders SET status = 'cancelled' WHERE id = 42; changes only matching rows. Omitting WHERE in UPDATE or DELETE affects every row in the table, so run the same condition as a SELECT first to confirm the target rows.