Summary: in this tutorial, you’ll learn how to use the PostgreSQL UNION operator to combine result sets of two queries into a single result set.
Getting started with the PostgreSQL UNION operator #
The UNION operator allows you to combine the result sets of two or more queries into a single result set. Here’s the syntax of the UNION operator:
SELECT column1, column2
FROM tableA;
UNION
SELECT column1, column2
FROM tableB;Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)In this syntax:
- First, provide two
SELECTstatements that you want to combine the result sets. - Second, use the
UNIONkeyword between the two queries.
The UNION operator appends the result set of the second SELECT statement to the result set of the first SELECT statement. Additionally, it removes duplicate rows from the final result set: