NOT: Exclude Matching Rows

The NOT keyword excludes rows that match a condition.
It turns a condition around: true becomes false, and false becomes true.

Syntax

SELECT column1, column2, ... FROM table_name
WHERE NOT condition;

Example 1: Employees not in IT, Sales or Finance

SELECT name, department FROM employees
WHERE NOT department = 'IT'
  AND NOT department = 'Sales'
  AND NOT department = 'Finance';

Output:

 name  | department 
-------+------------
 Alice | HR
 David | Marketing
 Ryan  | Marketing
 Anna  | HR
(4 rows)

This returns all employees who are not in IT, Sales or Finance. Only HR and Marketing are left.

Example 2: Employees who are not older than 25

SELECT name, age FROM employees
WHERE NOT age > 25;

Output:

  name  | age 
--------+-----
 John   |  25
 Mike   |  24
 Olivia |  25
 Anna   |  24
(4 rows)

NOT age > 25 means the same as age <= 25.


Tip

You can also combine NOT with IN, LIKE and BETWEEN. You will learn these in the next lessons.

In the exercise, use NOT to exclude the employees younger than 25.