Tutorialsteacher

Follow Us

PostgreSQL EXCEPT Operator

PostgreSQL EXCEPT operator is used to combine the result set of two or more SELECT statements into a single result set. The EXCEPT operator returns all rows from the first SELECT statement that are not returned by the second SELECT statement.

The UNION, UNION ALL, INTERSECT, and EXCEPT operators generally used with same kind of tables to find the same or different data in tables.

Syntax
SELECT Query 1
EXCEPT 
SELECT Query 2
EXCEPT
SELECT Query 3
...

The following rule must be applied to combine the result set of two or more quires using the EXCEPT operator.

  • There must be the same number of columns or expressions in each SELECT statement.
  • The corresponding columns in each SELECT statement must have similar data types.

We will use the following Employee and Person tables to understand how EXCEPT operator works.

The following example demonstrates the EXCEPT operator with the SELECT query.

Example: EXCEPT Operator
SELECT first_name, last_name FROM Employee
EXCEPT
SELECT first_name, last_name FROM Person;

The following displays the result of the above query in pgAdmin.

The above result includes the rows from the first SELECT statement which is not available in the result set of the second SELECT statement.

The EXCEPT operator matches the value in each column in both the queries. If a value of any column does not match with the same column (in a sequence) in the second query then it includes that row in the result. For example, if the last_name value is ‘john’ where the first_name is ‘Annie’ then it would be considered as a different row than any of the rows in the Person table because the last_name in the Person table is ‘Smith’.

Let’s use ORDER BY to fetch the same result set with descending order of first_name.

Example: EXCEPT Operator
SELECT first_name, last_name FROM Employee
EXCEPT
SELECT first_name, last_name FROM Person ORDER BY first_name DESC;

It will raise an error if the number of columns and the types of columns are not matching. For example, the following query includes three columns in the first SELECT query whereas only two columns in the second SELECT query and so it will raise an error.