Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

PostgreSQL EXCEPT Operator

Summary: in this tutorial, you will learn how to use the PostgresQL EXCEPT operator
to return the rows in the first query that do not appear in the output of the second query.

Introduction to the PostgreSQL EXCEPT operator


Like the UNION and INTERSECT operators, the EXCEPT operator returns rows by
comparing the result sets of two or more quires.

The EXCEPT operator returns distinct rows from the first (left) query that are not in the
output of the second (right) query. The following illustrates the syntax of the EXCEPT
operator.

1 SELECT column_list
2 FROM A
3 WHERE condition_a
4 EXCEPT
5 SELECT column_list
6 FROM B
7 WHERE condition_b;

To combine the queries using the EXCEPT operator, you must obey the following rules:

 The number of columns and their orders must be the same in the two queries.
 The data types of the respective columns must be compatible.

The following Venn diagram illustrates the result of the of EXCEPT operator that apply
to the A and B tables.

PostgreSQL EXCEPT example


Let’s take a look at the film and inventory tables of the sample database.

The following query returns the films in the film table.


1 SELECT
2 film_id,
3 title
4 FROM
5 film
6 ORDER BY
7 title;

The following query returns the films that are in the inventory:

1 SELECT
2 distinct inventory.film_id,
3 title
4 FROM
5 inventory
6 INNER JOIN film ON film.film_id = inventory.film_id
7 ORDER BY title;
Both queries return a result set that consists of two columns: film_id and title.

To get the films that are not in the inventory, you use the EXCEPT operator as follows:

1 SELECT
2 film_id,
3 title
4 FROM
5 film
6 EXCEPT
7 SELECT
8 DISTINCT inventory.film_id,
9 title
10 FROM
11 inventory
12 INNER JOIN film ON film.film_id = inventory.film_id
13 ORDER BY title;
Notice that we placed the ORDER BY clause at the end of the statement to sort the
films by their titles. If you place the ORDER BY clause in each query, the final result may
not be sorted because each query will sort the result set by the title column and after
that the EXCEPT operator is applied to the both queries.

In this tutorial, we have shown you how to use the PostgreSQL EXCEPT operator to
combine two queries to get the rows in the first query that do not appear in the output of
the second query.

You might also like