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:

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.