Negating conditions with NOT #
The NOT keyword flips a condition: rows that used to match are excluded, and rows that used to fail now match.
Syntax #
SELECT
column_name
FROM
table_name
WHERE
NOT condition;
Example #
Instead of listing every category we do want, we can ask for every product that is not in the 'Office' category:
SELECT
*
FROM
products
WHERE
NOT category = 'Office';
Result:
+----+-------------------+-------------+-------+
| id | name | category | price |
+----+-------------------+-------------+-------+
| 1 | Wireless Mouse | Electronics | 19.99 |
| 2 | Bluetooth Speaker | Electronics | 45.5 |
| 3 | Yoga Mat | Fitness | 25.0 |
| 4 | Running Shoes | Fitness | 60.0 |
| 5 | Coffee Mug | Home | 8.5 |
| 6 | Desk Lamp | Home | 22.0 |
+----+-------------------+-------------+-------+
Notebook and Backpack, the two 'Office' products, are left out. NOT can be placed in front of any condition, including ones that use AND, OR, or the operators from earlier lessons.
Exercise #
Write a query that retrieves all columns from the products table, keeping only the rows where category is not 'Office'.
- The result has a
categorycolumn. - The result contains exactly the rows where
categoryis not'Office', and no others.
Solution
SELECT
*
FROM
products
WHERE
NOT category = 'Office';
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity