SQL NOT
NOT reverses a condition: rows are kept when the condition is false.
SELECT columns
FROM table_name
WHERE NOT condition;Basic NOT
All orders that are not delivered:
SELECT status, COUNT(*) AS orders
FROM orders
WHERE NOT status = 'delivered'
GROUP BY status
ORDER BY status;status | orders
-----------+-------
cancelled | 7
processing | 8
shipped | 9
(3 rows)
(Don't worry about GROUP BY yet — it just counts the rows per status.)
NOT with other operators
NOT reads naturally in front of IN, LIKE, BETWEEN and NULL:
| Form | Meaning |
|---|---|
NOT status = 'shipped' |
same as status <> 'shipped' |
country NOT IN ('USA', 'UK') |
none of the listed values |
name NOT LIKE 'C%' |
does not start with C |
price NOT BETWEEN 5 AND 50 |
below 5 or above 50 |
email IS NOT NULL |
value is present |
SELECT name, price
FROM products
WHERE category_id = 1
AND price NOT BETWEEN 4 AND 10
ORDER BY price;name | price
---------------+------
Orange Juice | 3.2
Chai Latte Mix | 11
Espresso Beans | 24.5
(3 rows)
SELECT name, country
FROM suppliers
WHERE country NOT IN ('UK', 'USA', 'France', 'Spain')
ORDER BY name;name | country
-----------------+------------
Alpine Dairy Co. | Switzerland
Byte Press | India
Hearth & Home | Norway
Volt Gadgets | Japan
(4 rows)
NOT with parentheses
NOT applies to the condition directly after it. To negate a combination, wrap it in parentheses. Customers that are not (in Germany or France):
SELECT COUNT(*) AS customers
FROM customers
WHERE NOT (country = 'Germany' OR country = 'France');customers
---------
21
(1 row)
By De Morgan's law, NOT (A OR B) is the same as NOT A AND NOT B.
NOT and NULL
NOT NULL is still NULL — unknown stays unknown. That means NOT does not return rows whose value is missing:
SELECT COUNT(*) AS with_example_email
FROM customers
WHERE email LIKE '%@example.com';
SELECT COUNT(*) AS not_example_email
FROM customers
WHERE NOT email LIKE '%@example.com';
SELECT COUNT(*) AS email_missing
FROM customers
WHERE email IS NULL;with_example_email
------------------
21
(1 row)
not_example_email
-----------------
0
(1 row)
email_missing
-------------
4
(1 row)
21 + 0 is not 25: the four customers without e-mail are in neither group. To include them, write WHERE NOT email LIKE '%@example.com' OR email IS NULL.
Note: For NULL checks always use
IS NULL/IS NOT NULL.email = NULLandNOT email = NULLare both unknown for every row.
Test yourself
Which is equivalent to NOT (price < 5)?
- price > 5
- price >= 5
- price <> 5
- price <= 5
Does WHERE NOT email = 'x@example.com' return customers whose email is NULL?
- Yes
- No
- Only in SQLite
- Only if there is an index
NOT (A OR B) equals…
- NOT A OR NOT B
- NOT A AND NOT B
- A AND B
- NOT A OR B