Using the Union join

The PostgreSQL UNION clause is used to combine the results of two or more SELECT statements without returning any duplicate rows.

The basic rules to combine two or more queries using the UNION join are as follows:

  • The number and order of columns of all queries must be the same
  • The data types of the columns on involving table in each query must be same or compatible
  • Usually, the returned column names are taken from the first query

By default, the UNION join behaves like DISTINCT, that is, eliminates the duplicate rows; however, using the ALL keyword with the UNION join returns all rows, including the duplicates, as shown in the following example:

SELECT <column_list>
FROM  table 
WHERE  condition
GROUP BY <column_list> [HAVING ] condition ...

Get PostgreSQL Development Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.