Open In App

PostgreSQL – NOT IN operator

The PostgreSQL NOT IN operator works exactly opposite to that of the IN operator. It is used to filter query results excluding the specified values from the list of values.

The syntax for using NOT IN operator with the WHERE clause to check against a list of values (except for the specified values) which returns a boolean value depending upon the match is as below:



Syntax: value NOT IN (value1, value2, …)

The syntax for using NOT IN operator to return the matching values(except for the specified values) in contrast with the SELECT statement is as below:



Syntax: value NOT IN (SELECT value FROM tbl_name);

For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link.

Now, let’s look into a few examples.
Example 1:
Here we will query for all rentals where the customer_id is not 10 or 12, from the “rental” table in our sample database.

SELECT
    customer_id,
    rental_id,
    return_date
FROM
    rental
WHERE
    customer_id NOT IN (10, 12);

Output:

Example 2:
Here we will query for all customers where the customer_id is not 10 or 12, from the “customer” table in our sample database.

SELECT
    customer_id,
    first_name,
    last_name
FROM
    customer
WHERE
    customer_id NOT IN (10, 12);

Output:

Article Tags :