![]() |
VOOZH | about |
The PostgreSQL UNION operator is a powerful tool used to combine result sets from multiple queries into a single result set. It helps in consolidating data from different sources, making it easier to analyze and report.
From this article, we can better understand the UNION Operator in PostgreSQL
SELECT
column_1,
column_2
FROM
table_name_1
UNION
SELECT
column_1,
column_2
FROM
table_name_2;
The below rules need to be followed while using a UNION operator:
Note: The UNION operator removes all duplicate rows from the query set.
Let's look into some examples of the UNION operator by setting up two sample tables in a sample database(say, sales2020). Let's say table 'sales2020q1' represents the sales of a particular product in the first quarter of 2020 and 'sales2020q2' represents the sales in the second quarter of the same year.
Now let's set up the database following the below procedures. Create the 'sales2020' database using the below command:
Now that our sample database is ready. Let's implement the UNION operator in a few examples.
Here we will use the UNION operator to combine data from both 'sales2020q1' and 'salese2020q2' tables.
Query:
SELECT * FROM
sales2020q1
UNION
SELECT * FROM
sales2020q2;
Output:
👁 PostgreSQL UNION operator ExampleExplanation: This query combines the rows from both tables into a single result set, removing duplicate rows.
Here we will sort the combined result returned by the UNION operator in defending order of "id" by using the ORDER BY clause after combining the data from both 'sales2020q1' and 'salese2020q2' tables.
SELECT * FROM
sales2020q1
UNION ALL
SELECT * FROM
sales2020q2
ORDER BY
name ASC,
amount DESC;
Output:
👁 PostgreSQL UNION operator ExampleExplanation: This query combines the rows from both tables without removing duplicates (UNION ALL), and sorts the results as specified.
- The column names in the result set of a
UNIONoperation are taken from the firstSELECTstatement.- Using
UNIONinstead ofUNION ALLcan be slower becauseUNIONremoves duplicates by sorting and then eliminating duplicates, which can be computationally intensive.- Be aware that
NULLvalues are treated as equal when removing duplicates in aUNIONoperation. Thus, rows withNULLvalues in the same positions will be considered duplicates.UNIONremoves duplicate rows. However, if duplicates are essential for your use case, useUNION ALLto retain all rows.