TExcelTAD
Home › SQL › SQL NOT

SQL NOT

NOT reverses a condition: rows are kept when the condition is false.

sql
SELECT columns
FROM table_name
WHERE NOT condition;

Basic NOT

All orders that are not delivered:

sql · try it yourself
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
sql · try it yourself
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)
sql · try it yourself
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):

sql · try it yourself
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:

sql · try it yourself
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 = NULL and NOT email = NULL are both unknown for every row.

Test yourself

Which is equivalent to NOT (price < 5)?

  1. price > 5
  2. price >= 5
  3. price <> 5
  4. price <= 5

Does WHERE NOT email = 'x@example.com' return customers whose email is NULL?

  1. Yes
  2. No
  3. Only in SQLite
  4. Only if there is an index

NOT (A OR B) equals…

  1. NOT A OR NOT B
  2. NOT A AND NOT B
  3. A AND B
  4. NOT A OR B