SQL Not
SQL NOT Operator
The NOT operator is used to exclude records that match a condition. It is typically used together with WHERE.
Basic Syntax
SELECT column1, column2 FROM table_name WHERE NOT condition;
Example: Exclude a Country
Return customers who are not from the USA:
SELECT name, country FROM customers WHERE NOT country = 'USA';
This is equivalent to:
SELECT name, country FROM customers WHERE country <> 'USA';
NOT with IN
NOT IN excludes rows that match any value in a list.
SELECT name, country
FROM customers
WHERE country NOT IN ('USA', 'Canada');
NOT with BETWEEN
NOT BETWEEN excludes values inside a range (it returns values outside the range).
SELECT name, price FROM products WHERE price NOT BETWEEN 50 AND 100;
NOT with LIKE
NOT LIKE excludes values that match a pattern.
SELECT name FROM customers WHERE name NOT LIKE 'A%';
NOT with EXISTS
NOT is also used with EXISTS (covered later) to exclude rows based on a subquery result.
Important Note About NULL
NULL means “unknown”. Comparisons with NULL do not behave like normal true/false logic. If a column can be NULL, conditions like NOT IN may return unexpected results when NULL is involved.
When you need to include or exclude NULL values explicitly, use IS NULL or IS NOT NULL.
SELECT name, phone FROM customers WHERE phone IS NOT NULL;
Common Mistakes
- Forgetting that NULL is not equal to anything (use IS NULL / IS NOT NULL)
- Using NOT without being clear about parentheses in complex logic
- Using NOT IN when the compared column may contain NULL values
Next Step
Continue with SQL INSERT INTO to learn how to add new records to a table.