AND, OR and NOT example
SELECT name, category, stock
FROM products
WHERE (category = 'Accessories' OR category = 'Audio')
AND stock > 0
ORDER BY name;Check the result with small data
We only want Audio or Accessories products that are not out of stock.
WITH products(name, category, stock) AS (
VALUES ('Mouse','Accessories',3),
('Headphones','Audio',0),
('Monitor','Displays',5)
)
SELECT name FROM products
WHERE (category = 'Audio' OR category = 'Accessories')
AND NOT stock = 0;| name |
|---|
| Mouse |
The parentheses group the categories before AND is applied. Mouse meets both conditions; Headphones fails on stock and Monitor on category.
Check your understanding: How would the result change if you removed NOT?
Show answer
Without NOT, the condition becomes stock = 0: it would return Headphones, which is Audio and out of stock, instead of Mouse.
What changes from case to case
Precedence can change the filter
NOT is evaluated before AND, and AND before OR. Even if you know that precedence, use parentheses when multiple conditions express a business rule: they reduce ambiguity and make the query easier to review.
WHERE (category = 'Accessories' OR category = 'Audio')
AND stock > 0;Read the parentheses like a statement. First it accepts Accessories or Audio; then it requires positive stock for either group.
What changes when NULL appears
A comparison such as discount > 0 is neither true nor false when discount equals NULL: its result is unknown. Negating it with NOT does not make that case true either.
WHERE discount IS NULL
OR discount <= 0;If you need to treat missing values as a case of their own, express it with IS NULL or IS NOT NULL; do not rely on an ordinary comparison.
Turning a rule into groups of conditions
Write the rule out in words first. «Active customers from London or Leeds» usually means being active is required for both cities. The form active = 1 AND (city = 'London' OR city = 'Leeds') makes that intent visible. Without parentheses, the Leeds criterion can let inactive people in, because AND takes precedence over OR.
A test set containing only active customers will not reveal the bug. Include an inactive customer in each city, an active one outside both, and one with an unknown city. Work out who should appear before running the query. Those rows represent the boundaries of the rule, not just more examples like the ones that already pass.
Negating a condition does not automatically include unknown values. NOT (city = 'London') does not keep a null city as if it were a different city. If you want to include it, you need to express that alternative explicitly. To rework complex conditions, separate each group and check its result with nulls; a rewrite that looks equivalent in everyday language can change who ends up in the report.
Technical questions: SQLite: expressions and type conversions (opens in a new tab).