Ira SQL ProIra SQL Pro

NOT Operator

beginnerfiltering
2 min read

What is the NOT Operator?

NOT negates a Boolean condition. It flips true to false and false to true. Use it to find rows that do not match a given criterion.

Syntax

SELECT * FROM table_name
WHERE NOT condition;

Common usages:

WHERE NOT col = 'value'
WHERE col NOT IN ('a', 'b')
WHERE col NOT BETWEEN 10 AND 20
WHERE col NOT LIKE 'A%'
WHERE NOT EXISTS (subquery)

When to Use

  • Excluding specific values or ranges
  • Finding rows that do not match a pattern
  • Negating complex Boolean expressions

Key Points

  1. Negation — NOT reverses the truth value of the condition.
  2. NULL — NOT NULL is still NULL (unknown). Use IS NOT NULL instead.
  3. ReadabilityNOT col = 'x' can be written as col != 'x' or col <> 'x'.
  4. Combining — NOT has higher precedence than AND/OR. Use parentheses for clarity.
  5. NOT IN and NULLs — If the list in NOT IN contains NULL, no rows are returned. Be careful with NULL values.

Guided Practice

Solve the challenge below. Use hints when stuck and check your answer for instant feedback.

Practice challengeGuided learning mode

NOT Operator Challenge

Write a query that find students who are not 20 years old.

Expected result

All students except those aged 20.

Hidden checks

  • Returned rows and values
  • Output columns and result shape
  • Final database state after the query runs

Lesson guidance

What is the NOT Operator?

Initializing database...Each run starts from fresh sample data.

More Examples

NOT IN

Find products not in certain categories.

Initializing database...Each run starts from fresh sample data.

NOT LIKE

Find students whose name does not start with A.

Initializing database...Each run starts from fresh sample data.

Frequently Asked Questions

What is the difference between NOT IN and != ALL?
They are equivalent. NOT IN ('a','b') is the same as != ALL(ARRAY['a','b']).
Why does NOT IN with NULLs return no rows?
Because comparing any value to NULL yields unknown, and NOT unknown is still unknown. Filter NULLs from the list to avoid this.

Related Topics