MySQL NOT Operator
MySQL NOT Operator: Negating Conditions Safely
The MySQL NOT operator reverses the boolean result of a condition, returning rows where the condition evaluates to false. Developers combine NOT with IN, BETWEEN, LIKE, EXISTS, and IS NULL to exclude unwanted records.
Basic Syntax
Place NOT before a condition or inside compound predicates such as NOT IN and IS NOT NULL:
SELECT columns
FROM table_name
WHERE NOT condition;
Practical SQL Example
This query returns active items from demo_products while excluding discontinued and sample categories.
SELECT id, product_name, category, price
FROM demo_products
WHERE category NOT IN ('discontinued', 'sample')
AND deleted_at IS NULL
ORDER BY price DESC;
| id | product_name | category | price |
|---|---|---|---|
| 14 | Standing Desk | Furniture | 299.50 |
| 8 | Wireless Headphones | Electronics | 89.99 |
Common Mistakes and Best Practices
- Beware the
NOT IN+NULLTrap: If aNOT IN (subquery)list contains even a singleNULLvalue, the entire condition evaluates toUNKNOWNand returns zero rows. Filter outNULLinside the subquery (WHERE id IS NOT NULL) or preferNOT EXISTSfor subquery exclusion. - Understand Index Limits on Negation: Positive filters (
status = 'active') narrow down B-tree ranges efficiently, whereasNOT status = 'archived'often reads most of the table. Use positive allowlists whenever your status set is small. - Avoid Double Negatives: Replace
WHERE NOT is_disabled = 0withWHERE is_disabled = 0so queries stay clear to future reviewers.
Frequently Asked Questions
Why does WHERE id NOT IN (1, 2, NULL) return zero rows?
In SQL three-valued logic, id != NULL evaluates to UNKNOWN, making the entire AND-chained NOT IN check UNKNOWN.
Is NOT EXISTS safer than NOT IN for subqueries?
Yes, NOT EXISTS ignores NULL rows safely and handles correlated anti-joins cleanly in MySQL 8.
What is the difference between != and <> in MySQL?
Both mean "not equal to" and behave identically in MySQL; <> is the ANSI SQL standard form.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.