Postgresql Union Operator

PostgreSQL: UNION Operator

In this PostgreSQL post explains how to use the PostgreSQL UNION operator with syntax and examples.

Description

The PostgreSQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements.

Each SELECT statement within the UNION operator must have the same number of fields in the result sets with similar data types.

Syntax

The syntax for the UNION operator in PostgreSQL is:

SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
UNION
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions];

Parameters or Arguments

expression1, expression2, ... expression_n

The columns or calculations that you wish to retrieve.

tables

The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.

WHERE conditions

Optional. The conditions that must be met for the records to be selected.

Note

  • There must be same number of expressions in both SELECT statements.
  • Since the UNION operator by default removes all duplicate rows from the result set, providing the UNION DISTINCT modifier has no effect on the results.
  • The column names from the first SELECT statement in the UNION operator are used as the column names for the result set.

Example - Return single field

The following is an example of the PostgreSQL UNION operator that returns one field from multiple SELECT statements (and both fields have the same data type):

SELECT category_id
FROM products
UNION
SELECT category_id
FROM categories;

In this PostgreSQL UNION operator example, if a category_id appeared in both the products and categories table, it would appear once in your result set. The PostgreSQL UNION operator removes duplicates. If you do not wish to remove duplicates, try using the PostgreSQL UNION ALL operator.

Example - Using ORDER BY

The PostgreSQL UNION operator can use the ORDER BY clause to order the results of the query.

For example:

SELECT product_id, product_name
FROM products
WHERE product_id >= 24
UNION
SELECT category_id, category_name
FROM categories
WHERE category_name > 'Hardware'
ORDER BY 2;

In this PostgreSQL UNION operator, since the column names are different between the two SELECT statements, it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set. In this example, we've sorted the results by product_name / category_name in ascending order, as denoted by the ORDER BY 2.

The product_name / category_name fields are in position #2 in the result set.