Filtering Rows With WHERE: Comparison and Logical Operators
How WHERE decides which rows a query returns: the comparison operators, comparing numbers, text and dates, case sensitivity, AND, OR and NOT, operator precedence and the classic missing-parentheses bug, De Morgan's laws, and why NULL rows quietly disappear.
kvi5hnuCode Sprout team member11 min readOn this page
A table usually holds far more rows than you need. The WHERE clause keeps only the rows that satisfy a search condition. The database tests the condition once for each row from FROM. A row whose condition is true stays in the result, and every other row is dropped.
SELECT columns
FROM table_name
WHERE search_condition;
This article covers the building blocks of search conditions: the comparison operators and the logical operators AND, OR and NOT. The next article adds IN, BETWEEN and LIKE, and article 8 deals with NULL, which needs special care.
The examples use the same products table as article 5, with seven products in four categories.
Comparison operators
| Operator | Meaning | Example |
|---|---|---|
= | equal to | category = 'tents' |
<> | not equal to (standard) | category <> 'tents' |
!= | not equal to (accepted by every major product) | category != 'tents' |
< | less than | price < 50 |
> | greater than | stock > 0 |
<= | less than or equal to | price <= 89.95 |
>= | greater than or equal to | price >= 100 |
Each comparison evaluates to true or false, or to unknown when NULL is involved (article 8). Only rows where the whole condition is true are kept.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Numbers
SELECT name, price FROM products WHERE price >= 89.95 ORDER BY price;
-- Text: exact, case-sensitive comparison
SELECT name FROM products WHERE category = 'Tents';
SELECT name FROM products WHERE category = 'tents' ORDER BY product_id;
-- Text has an order too: names that sort before 'M'
SELECT name FROM products WHERE name < 'M' ORDER BY name;
-- Not equal: <> is standard, != is a common synonym
SELECT name, category FROM products WHERE category <> 'tents' AND category != 'packs' ORDER BY product_id;
name | price
-------------------+--------
Trail 30 backpack | 89.95
Ridge 2 tent | 249.99
Summit 4 tent | 489.00
(3 rows)
name
------
(0 rows)
name
---------------
Ridge 2 tent
Summit 4 tent
(2 rows)
name
------------------
Basecamp lantern
Day 18 backpack
Glow head torch
(3 rows)
name | category
------------------+----------
Glow head torch | lighting
Basecamp lantern | lighting
Merino socks | clothing
(3 rows)
What this shows:
- Numbers compare by value, as you'd expect.
price >= 89.95includes the backpack priced at exactly 89.95. - Text comparisons are exact.
category = 'Tents'found nothing, because the stored values are lowercase. In PostgreSQL and Oracle,=on text is case-sensitive. In MySQL and SQL Server, the default collation makes it case-insensitive, so the same query would find both tents. Article 36 covers collations and how to compare without regard to case. - Text has an order.
name < 'M'keeps names that sort beforeM. The order is decided by the column's collation. This database uses the simpleCcollation, which compares character codes, so all uppercase letters sort before all lowercase letters and'Zebra' < 'apple'is true. Language-aware collations, such asen_US, sort letters alphabetically regardless of case. <>and!=mean the same thing.<>is the standard spelling.
Comparing dates
Dates compare chronologically. Write date literals in ISO format, YYYY-MM-DD. Every product understands that format, while formats like 03/01/2026 are ambiguous and depend on settings. The standard form is a typed literal, DATE '2026-03-01'. A plain string '2026-03-01' also works in most products, because it's converted to the column's type.
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL,
total DECIMAL(8, 2) NOT NULL
);
INSERT INTO orders VALUES
(1, '2026-02-27', 'shipped', 120.00),
(2, '2026-03-01', 'shipped', 45.50),
(3, '2026-03-14', 'pending', 310.00),
(4, '2026-03-31', 'shipped', 99.00),
(5, '2026-04-02', 'returned', 60.00);
-- Dates compare chronologically; write them as ISO literals
SELECT order_id, placed_on FROM orders
WHERE placed_on >= DATE '2026-03-01' AND placed_on < DATE '2026-04-01'
ORDER BY order_id;
-- Text that looks like numbers compares character by character
SELECT '10' < '9' AS text_compare, 10 < 9 AS number_compare;
order_id | placed_on
----------+------------
2 | 2026-03-01
3 | 2026-03-14
4 | 2026-03-31
(3 rows)
text_compare | number_compare
--------------+----------------
t | f
(1 row)
The first query uses the safest pattern for "everything in March": >= the first day and < the first day of the next month. It's correct whatever the month length, and it keeps working if the column is later changed to a timestamp with a time of day. A condition like placed_on <= DATE '2026-03-31' would miss every order placed after midnight on March 31 if placed_on held times as well. Article 40 covers date ranges in depth.
The second query shows a trap: text that looks like numbers is still compared as text, character by character. '1' sorts before '9', so '10' < '9' is true. Store numbers in numeric columns, and dates in date columns, so that comparisons and sorting behave.
Mixing types
When the two sides of a comparison have different types, the database converts one of them, and products differ in how forgiving they are:
- PostgreSQL converts an untyped string literal to the other side's type, so
price > '50'works. It refuses comparisons it can't do sensibly:'abc' = 0is an error. - MySQL converts strings to numbers when comparing with a number, taking any leading digits. So
'abc' = 0is true, and'12abc' = 12is true too, with only a warning. This silently matches rows you didn't mean to match. - SQL Server and Oracle convert the string to a number, and fail with a conversion error if they can't.
The safe habit is to compare values of the same type: numbers with numbers, dates with typed date literals.
AND, OR and NOT
The logical operators combine conditions:
a AND bis true only when both are true.a OR bis true when at least one is true.NOT ais true whenais false.
When you mix AND and OR, precedence decides the grouping: NOT binds tightest, then AND, then OR. Comparison operators bind tighter than all three. That leads to one of the most common bugs in SQL:

CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Intended: tents or packs, but only those under 100
-- AND binds tighter than OR, so this means: tents, or (packs under 100)
SELECT name, category, price FROM products
WHERE category = 'tents' OR category = 'packs' AND price < 100
ORDER BY product_id;
-- Parentheses say what was meant
SELECT name, category, price FROM products
WHERE (category = 'tents' OR category = 'packs') AND price < 100
ORDER BY product_id;
-- NOT negates a whole condition
SELECT name, price, stock FROM products
WHERE NOT (price > 50 OR stock = 0)
ORDER BY product_id;
-- A NULL brand is neither equal nor unequal to 'Kestrel'
SELECT name, brand FROM products WHERE brand <> 'Kestrel' ORDER BY product_id;
name | category | price
-------------------+----------+--------
Ridge 2 tent | tents | 249.99
Summit 4 tent | tents | 489.00
Trail 30 backpack | packs | 89.95
Day 18 backpack | packs | 54.00
(4 rows)
name | category | price
-------------------+----------+-------
Trail 30 backpack | packs | 89.95
Day 18 backpack | packs | 54.00
(2 rows)
name | price | stock
------------------+-------+-------
Glow head torch | 34.50 | 40
Basecamp lantern | 27.00 | 15
Merino socks | 16.00 | 75
(3 rows)
name | brand
-----------------+--------
Ridge 2 tent | Alpina
Summit 4 tent | Alpina
Glow head torch | Lumen
Merino socks | Woolly
(4 rows)
- The first query was meant to find tents and packs under 100, but
ANDgrouped first. It returned every tent at any price, plus the cheap packs. Nothing warned about it: the query is valid, it just means something else. - The second query adds parentheses, and returns what was meant. Whenever a condition mixes
ANDandOR, add parentheses, even when the precedence happens to give the right answer. They cost nothing and tell the next reader what you intended. - The third query uses
NOTon a parenthesized condition: not (expensive or out of stock). By De Morgan's laws, that's the same as "not expensive and in stock", orprice <= 50 AND stock <> 0. When you negate a condition,NOT (a OR b)becomesNOT a AND NOT b, andNOT (a AND b)becomesNOT a OR NOT b. Getting this wrong is a frequent source of off-by-a-few-rows bugs. - The fourth query asked for products whose brand isn't Kestrel, and the lantern is missing, even though its brand certainly isn't Kestrel. Its brand is NULL, and comparing NULL with anything gives unknown, not true.
WHEREkeeps only true rows, so the lantern was silently dropped. If you want it, ask for it:WHERE brand <> 'Kestrel' OR brand IS NULL. Article 8 explains this three-valued logic.
Evaluation order and short-circuiting
SQL doesn't promise to evaluate a AND b left to right, or to skip b when a is false. The optimizer may test the conditions in any order, for example the cheaper one first, or the one an index can answer. So don't write conditions that depend on order to avoid an error, such as WHERE stock <> 0 AND price / stock > 5. The division may still run on a row with zero stock. Make each condition safe on its own: price / NULLIF(stock, 0) > 5. A CASE expression (article 11) is the one construct whose evaluation order is defined, apart from some corner cases with constants.
Writing conditions that can use indexes
A condition that compares a bare column with a value, such as price > 100 or placed_on >= DATE '2026-03-01', lets the database use an index on that column to jump straight to the matching rows. A condition that wraps the column in a calculation or function, such as price * 1.2 > 120 or EXTRACT(YEAR FROM placed_on) = 2026, usually can't use a plain index, so the database has to test every row. Where you can, move the arithmetic to the other side: price > 100 instead of price * 1.2 > 120, and a date range instead of extracting the year. Conditions that can use an index are called sargable (from "search argument able"). Article 55 explains why, and article 67 shows how to check.
Boolean columns
PostgreSQL and Oracle 23ai and later have a real BOOLEAN type. MySQL's BOOLEAN is a synonym for TINYINT(1), and SQLite stores 0 and 1, but both also accept a column directly as a condition:
SELECT name FROM products WHERE is_discontinued; -- same as = TRUE
SELECT name FROM products WHERE NOT is_discontinued;
SQL Server has no boolean type. It uses BIT (0 or 1), and you must compare explicitly: WHERE is_discontinued = 1.
What's current
- Oracle AI Database 26ai (since 23ai) supports the SQL
BOOLEANtype, so conditions likeWHERE is_activenow work in Oracle too. - Comparison semantics haven't changed in years. The differences that bite are still the default case sensitivity of text (case-sensitive in PostgreSQL and Oracle, case-insensitive by default in MySQL and SQL Server) and MySQL's lenient conversion of strings to numbers.
Common questions
Is <> or != better?
<> is the SQL standard. != works in every major product too. Pick one and use it consistently.
Are string comparisons case-sensitive?
It depends on the product and the column's collation. PostgreSQL and Oracle are case-sensitive by default. MySQL and SQL Server are case-insensitive with their default collations. SQLite is case-sensitive for = but case-insensitive for ASCII letters with LIKE. To be sure, compare LOWER(col) = LOWER(value), or use an explicit collation (article 36).
Do trailing spaces matter when comparing strings?
Sometimes. For CHAR(n) columns, trailing spaces are padding and are ignored. For VARCHAR, PostgreSQL compares exactly. SQL Server and older MySQL collations ignore trailing spaces in = comparisons, while MySQL 8's default collation doesn't. When it matters, trim the values (article 36).
Can a WHERE clause compare two columns?
Yes. For example, WHERE stock < reorder_level compares two columns of the same row. Either side of a comparison can be any expression.
Does the order of conditions joined by AND affect performance? Not in any modern database. The optimizer reorders conditions as it sees fit. Write them in whatever order is clearest.
Why did my query return no rows, when I'm sure the value is there?
The usual suspects are case ('Tents' versus 'tents'), leading or trailing spaces in the data, a NULL where you expected a value, a date compared with a time included, or AND and OR grouping differently from what you meant.
Summary
WHEREkeeps the rows for which the search condition is true. False and unknown rows are dropped.- The comparison operators are
=,<>(or!=),<,>,<=and>=. They work on numbers, text (ordered by collation) and dates. - Text equality is case-sensitive in PostgreSQL and Oracle, but case-insensitive by default in MySQL and SQL Server.
- Write dates as ISO literals (
DATE '2026-03-01'), and select a period with>=startAND <next start. - Compare values of the same type. MySQL's lenient conversion (
'abc' = 0is true) is a common trap. NOTbinds tighter thanAND, which binds tighter thanOR. Always add parentheses when mixingANDandOR.- Negate with De Morgan's laws:
NOT (a OR b)isNOT a AND NOT b. - A comparison with NULL is unknown, so rows with NULL fail both
=and<>.
Practice questions
Write a query for products that cost less than 50 and are in stock, or that belong to the tents category (at any price and stock level).
Answer
SELECT name, category, price, stock
FROM products
WHERE (price < 50 AND stock > 0)
OR category = 'tents'
ORDER BY product_id;
The parentheses aren't strictly needed here, because AND already binds tighter than OR. They make the intent obvious, though. This returns the head torch, lantern and socks (cheap and in stock) plus both tents.
Rewrite WHERE NOT (category = 'packs' AND stock = 0) without NOT. Which products does it return?
Answer
By De Morgan's laws, NOT (a AND b) is NOT a OR NOT b, so the condition becomes:
WHERE category <> 'packs' OR stock <> 0
It returns every product except the out-of-stock pack, the Day 18 backpack, so six products in total.
A report should list orders placed in 2026. The developer writes WHERE placed_on BETWEEN '2026-01-01' AND '2026-12-31'. When is this correct, and what's the safer form?
Answer
It's correct if placed_on is a DATE with no time of day. If the column is a timestamp, '2026-12-31' means midnight at the start of December 31, so orders placed later that day are missed. The safer form works for both types:
WHERE placed_on >= DATE '2026-01-01'
AND placed_on < DATE '2027-01-01'
Why does SELECT name FROM products WHERE brand <> 'Kestrel' not return the Basecamp lantern? Fix the query so it does.
Answer
The lantern's brand is NULL. NULL <> 'Kestrel' evaluates to unknown, not true, and WHERE keeps only rows where the condition is true. To include rows with no brand, ask for them explicitly:
SELECT name
FROM products
WHERE brand <> 'Kestrel' OR brand IS NULL;
PostgreSQL, SQLite and SQL Server 2022 and later also have a NULL-safe comparison, brand IS DISTINCT FROM 'Kestrel', which treats NULL as an ordinary value. MySQL spells it NOT (brand <=> 'Kestrel'). Article 8 covers both.
Previous: SQL SELECT Basics: Choosing Columns, Expressions and Aliases
Next: SQL IN, BETWEEN and LIKE: Lists, Ranges and Pattern Matching

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.